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