Python使用scrapy采集数据时为每个请求随机分配user-agent的方法,scrapyuser-agent
Python使用scrapy采集数据时为每个请求随机分配user-agent的方法,scrapyuser-agent
本文实例讲述了Python使用scrapy采集数据时为每个请求随机分配user-agent的方法。分享给大家供大家参考。具体分析如下:
通过这个方法可以每次请求更换不同的user-agent,防止网站根据user-agent屏蔽scrapy的蜘蛛
首先将下面的代码添加到settings.py文件,替换默认的user-agent处理模块
复制代码 代码如下:DOWNLOADER_MIDDLEWARES = {
'scraper.random_user_agent.RandomUserAgentMiddleware': 400,
'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware': None,
}
自定义useragent处理模块
复制代码 代码如下:from scraper.settings import USER_AGENT_LIST
import random
from scrapy import log
class RandomUserAgentMiddleware(object):
def process_request(self, request, spider):
ua = random.choice(USER_AGENT_LIST)
if ua:
request.headers.setdefault('User-Agent', ua)
#log.msg('>>>> UA %s'%request.headers)
希望本文所述对大家的Python程序设计有所帮助。
相关内容
- python threading模块操作多线程介绍,pythonthreading
- 在Docker上部署Python的Flask框架的教程,dockerflask
- python单例模式实例分析,python实例分析
- Python MySQLdb模块连接操作mysql数据库实例,mysqldbmysql
- Python中关于字符串对象的一些基础知识,python字符串
- python内存管理分析,python内存管理
- Python HTMLParser模块解析html获取url实例,pythonhtmlparser
- python uuid模块使用实例,pythonuuid
- python文件写入实例分析,
- python自然语言编码转换模块codecs介绍,pythoncodecs
评论关闭