我正在使用 scrapy。我想为每个请求生成一个唯一的用户代理。我有以下内容:
class ContactSpider(Spider):
name = "contact"
def getAgent(self):
f = open('useragentstrings.txt')
agents = f.readlines()
return random.choice(agents).strip()
headers = {
'user-agent': getAgent(),
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache"
}
def parse(self, response):
open_in_browser(response)
getAgent 从以下形式的列表中生成代理:
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
但是当我运行它时我得到:
File "..spiders\contact_spider.py, line 35, in <module>
class ContactSpider(Spider):
File "..spiders\contact_spider.py", line 54, in ContactSpider
'user-agent': getAgent(),
TypeError: getAgent() takes exactly 1 argument (0 given)
请您参考如下方法:
getAgent() 是一个实例方法,并希望将 ContactSpider 实例视为参数。但是,问题是,你不需要这个函数成为你的蜘蛛类的成员 - 将它移动到一个单独的“helpers”/“utils”/“libs”模块并导入:
from helpers import getAgent
class ContactSpider(Spider):
name = "contact"
headers = {
'user-agent': getAgent(),
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache"
}
def parse(self, response):
open_in_browser(response)
另请参阅:Difference between Class and Instance methods .
或者,作为替代方法,有一个 scrapy-fake-user-agent可以无缝和随机地轮换用户代理的 Scrapy 中间件。用户代理字符串由 fake-useragent module 提供.
