当前位置: 首页 > 后端技术 > Python

28.Cookie禁用,自动限速,自定义蜘蛛设置,反爬机制

时间:2023-03-26 00:44:53 Python

资料:http://www.swpan.cn]【百度云搜索,搜索各种资料:http://www.bdyss。cn]Cookiedisable是指在Scrapy配置文件settings.py中禁用cookiedisable,可以通过禁用cookie来防止被识别为爬虫。请注意,它仅适用于不需要登录的网页。禁用cookie后无法登录。在settings.py中禁用cookieDisableCOOKIES_ENABLED=FalseDisablecookies#禁用cookie(默认启用)COOKIES_ENABLED=False自动限速Scrapy默认没有限速,只要遇到一个URL,它将无间隙地访问。.这个选项可以用来限制爬取速度,减轻服务器压力。还支持小数(以秒为单位)#为同一网站的请求配置延迟(默认值:0)#参见http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay#另见autothrottlesettingsanddocsDOWNLOAD_DELAY=10AUTOTHROTTLE_ENABLED=True打开速度限制,启用AutoThrottle扩展#启用和配置AutoThrottle扩展(默认禁用)#参见http://doc.scrapy.org/en/latest/topics/autothrottle.htmlAUTOTHROTTLE_ENABLED=true自定义爬虫的设置,即为每个爬虫分别在配置文件中设置值,会覆盖settings.py中相同的设置custom_settings={key-valuepair}为每个爬虫在配置文件中设置值单独爬虫,settings.py中相同的设置会被覆盖,在爬虫文件中设置例如:#-*-coding:utf-8-*-importscrapyfromscrapy.httpimportRequest,FormRequestclassPachSpider(scrapy.Spider):#定义爬虫类,必须继承scrapy.Spidername='pach'#设置爬虫名称allowed_domains=['www.kuaidaili.com']#抓取域名custom_settings={"COOKIES_ENABLED":True#覆盖settings.py同样的设置,开启COOKIES}defstart_requests(self):#启动url函数,会替换start_urls"""第一次请求登录页面,设置opencookie获取cookie,设置回调函数"""return[Request(url='http://www.kuaidadaili.com/free/inha/2/',meta={'cookiejar':1},#打开Cookies记录,将Cookies传给回调函数callback=self.parse)]defparse(self,response):title=response.xpath('//*[@id="list"]/table/tbody/tr')