我正在尝试创建一个scraper为cloudfare保护的网站使用cfscrape
,privoxy
和tor,和scrapy_fake_useragent
我使用cfscrape
python extension绕过带有scrapy的cloudfare保护,并使用scrapy_fake_useragent
将随机的真实的USER_AGENT信息注入到头文件中。
如cfscrap文档所示:您必须使用相同的用户代理字符串来获取令牌并使用这些令牌发出请求,否则Cloudflare会将您标记为bot。
To collect cookie needed by `cfscrape`, i need to redefine the `start_request` function into my spider class, like this :
def start_requests(self):
cf_requests = []
for url in self.start_urls:
token, agent = cfscrape.get_tokens(url)
self.logger.info("agent = %s", agent)
cf_requests.append(scrapy.Request(url=url,
cookies= token,
headers={'User-Agent': agent}))
return cf_requests
我的问题是start_requests
收集的user_agent
与scrapy_fake_useragent
随机选择的user_agent
不一样,如您所见:
017-01-11 12:15:08 [airports] INFO: agent = Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0
2017-01-11 12:15:08 [scrapy.core.engine] INFO: Spider opened
2017-01-11 12:15:08 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-01-11 12:15:08 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-01-11 12:15:08 [scrapy_fake_useragent.middleware] DEBUG: Assign User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10 to Proxy http://127.0.0.1:8118
我在settings.py
中定义了我的扩展,顺序如下:
RANDOM_UA_PER_PROXY = True
HTTPS_PROXY = 'http://127.0.0.1:8118'
COOKIES_ENABLED = True
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
'scrapy_fake_useragent.middleware.RandomUserAgentMiddleware': 400,
'flight_project.middlewares.ProxyMiddleware': 100,
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware':110,
}
我需要相同的user_agent
,那么我如何将scrapy_fake_useragent
随机提供的用户代理传递/获取到cfscrape
扩展的start_requests
方法中呢?
1条答案
按热度按时间yx2lnoni1#
最后在
scrapy_user_agent
开发者的帮助下找到了答案。在settings.py
中取消激活'scrapy_fake_useragent.middleware.RandomUserAgentMiddleware': 400
行,然后编写以下源代码: