Scrapy爬虫系列笔记之九:反爬虫之Useragent设置以及开源项目的结合_by_书䜣

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章