我用以下方法创建了此类parse()
:
class PitchforkSpider(scrapy.Spider):
name = "pitchfork_reissues"
allowed_domains = ["pitchfork.com"]
#creates objects for each URL listed here
start_urls = [
"http://pitchfork.com/reviews/best/reissues/?page=1",
"http://pitchfork.com/reviews/best/reissues/?page=2",
"http://pitchfork.com/reviews/best/reissues/?page=3",
]
def parse(self, response):
for sel in response.xpath('//div[@class="album-artist"]'):
item = PitchforkItem()
item['artist'] = sel.xpath('//ul[@class="artist-list"]/li/text()').extract()
item['reissue'] = sel.xpath('//h2[@class="title"]/text()').extract()
return item
然后我导入属于的module
地方class
:
from blogs.spiders.pitchfork_reissues_feed import *
并尝试parse()
在其他情况下致电:
def reissues(self):
pitchfork_reissues = PitchforkSpider()
reissues = pitchfork_reissues.parse('response')
print (reissues)
但出现以下错误:
pitchfork_reissues.parse('response')
File "/Users/vitorpatalano/Documents/Code/Soup/Apps/myapp/blogs/blogs/spiders/pitchfork_reissues_feed.py", line 21, in parse
for sel in response.xpath('//div[@class="album-artist"]'):
AttributeError: 'str' object has no attribute 'xpath'
我想念什么?
您正在parse
使用字符串文字进行调用:
reissues = pitchfork_reissues.parse('response')
我猜应该是变量名吗?像这样:
reissues = pitchfork_reissues.parse(response)
编辑
Spider的parse
方法需要scrapy.http.Response
第一个参数的实例,而不是包含单词“ response”的字符串文字。
我自己并没有使用Scrapy,所以我只知道我在文档中读过什么,但是显然这样的Response实例通常是由“下载器”创建的。
似乎您正在尝试parse
在Scrapy的常规工作流程之外调用Spider的方法。在那种情况下,我认为您有责任创建这样的Response,并在调用它的parse
method时将其传递给Spider 。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句