Scrapy爬虫系列笔记之九:反爬虫之Useragent设置以及开源项目的结合_by_书訢
2018-02-07 21:36
435 查看
3.scrapy反爬虫技术
3.1User-agent
反爬:网站发现某个时段访问的user-agent都是python,直接限制访问对应方式:user-agent模拟浏览器
方式一.settings文件中写入一个预置list,在爬虫文件中给header的user-Agent进行设置
settings.py文件中将user-agent写入,这里我采用的是写一个list,之后爬虫文件只需要import就可以了
#settings.py user_agent_list[ "" "" "" "" "" "" ]
接下来我们编写爬虫文件
#爬虫文件,parse函数中每次yeild之前设置头就OK from settings import user_agent_list ''' 省略重复代码 ''' import random random_index=random.randint(0,len(user_agent_list)-1) random_agent = user_agent_list[random_index] yeild .......
方式二.中间件进行编写,从而降低代码耦合度,这样写多个文件也可以操作了
fake-useragent的使用
#使用github的开源项目 pip install fake-useragent即可 from fake_useragent import UserAgent class RandomUserAgentMiddleware(object): #随即更换user-agent def __init__(self, crawler): super(RandomUserAgentMiddlware, self).__init__ self.ua = UserAgent() @classmethod def from_crawler(cls, crawler): return cls(crawler) def process_request(self, request ,spider): request.header.setdefault('User-Agent',self.ua.random)
注意同时将下载的中间件设置进行修改
原来默认的一定要设置为None,不然只是设置一个大一点的数字只是晚一些执行,还是会将header给覆盖掉
#middlewares.py DOWNLOADER_MIDDLEWARES = { 'ArticleSpider.middlewares.MyCustomDownloaderMiddleware': None, 'ArticleSpider.middlewares.RandomUserAgentMiddleware': 1,}
笔记一到十链接
http://blog.csdn.net/sx_csu2016sw/article/details/79284369
http://blog.csdn.net/sx_csu2016sw/article/details/79284427
http://blog.csdn.net/sx_csu2016sw/article/details/79284449
http://blog.csdn.net/sx_csu2016sw/article/details/79284469
http://blog.csdn.net/sx_csu2016sw/article/details/79284481
http://blog.csdn.net/sx_csu2016sw/article/details/79284491
http://blog.csdn.net/sx_csu2016sw/article/details/79284509
http://blog.csdn.net/sx_csu2016sw/article/details/79284525
http://blog.csdn.net/sx_csu2016sw/article/details/79284547
http://blog.csdn.net/sx_csu2016sw/article/details/79284567
相关文章推荐
- Scrapy爬虫系列笔记之十:反爬虫之动态代理,限速,登录以及验证码_by_书訢
- Scrapy爬虫系列笔记之二:搭建python以及其虚拟环境_by_书訢
- Scrapy爬虫系列笔记之三:正则表达式,url去重策略以及遍历算法_by_书訢
- Scrapy爬虫系列笔记之四:爬取实战之创建爬虫以及Scapy环境搭建_by_书訢
- Scrapy爬虫系列笔记之五:静态无验证网站的爬取以及xpath和css选择器_by_书訢
- Scrapy爬虫系列笔记之六:使用item以及对得到的数据进行存储以及处理_by_书訢
- 爬虫知识5:常见反爬虫机制——User-Agent和代理IP设置
- 开源you-get项目爬虫,以及基于python+selenium的自动测试利器
- Linux企业级项目实践之网络爬虫(13)——处理user-agent
- java给爬虫设置User-Agent(绕过最表面的反爬虫机制)
- Linux企业级项目实践之网络爬虫(13)——处理user-agent
- 【开源项目13】Volley框架 以及 设置request超时时间
- 【开源项目13】Volley框架 以及 设置request超时时间
- 关于设置爬虫随机user-agent的一点尝试
- Scrapy爬虫系列笔记之七:ItemLoader解决代码难以维护的噩梦_by_书訢
- 【开源项目13】Volley框架 以及 设置request超时时间
- Scrapy爬虫系列笔记之八:Selenium进行动态网站爬取_by_书訢
- chencang-----为爬虫设置User-Agent
- Scrapy爬虫系列笔记之一:总纲_by_书訢
- py3 爬虫设置user-agent