TypeError:只取一个参数(给定0) - Scrapy

时间:2016-09-10 00:17:56

标签: python scrapy

我正在使用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)

1 个答案:

答案 0 :(得分:2)

getAgent()实例方法,希望将ContactSpider实例视为参数。但问题是,您不需要此功能成为您的蜘蛛类的成员 - 将其移动到单独的&#34;帮助&#34; /&#34; utils&#34; /&#34 ;库&#34;模块和导入:

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提供。