真的很难指出问题所在,因为我无法使用您提供的代码重现错误。
我不知道你的代码到底有什么问题,但我可以给你一些改进代码的提示:
for regularListingContainer in body.xpath('//div[@class="search-item regular-ad"]'):
link = str(regularListingContainer.re('href="(.*)" class="title">'))
您可以多次调用 xpath 或 css 选择器,在抓取时坚持使用 scrapy 库更快,您可以执行 body.xpath().xpath().css() 来获取您只需 extract() 它的字符串
for regularListingContainer in body.xpath('//div[@class="search-item regular-ad"]'):
link = regularListingContainer.xpath('a[contains(@class, "title")]/@href').extract_first()
大多数时候处理链接时最好使用urljoin(),让scrapy 完成繁重的工作并处理相对路径或绝对路径
link = regularListingContainer.xpath('a[contains(@class, "title")]/@href').extract_first()
yield Request(urljoin(link), callback=self.parse_dir_contents)
Scrapy 使用多线程意味着每次产生任何东西时,它都会打开一个线程并使其彼此异步运行。这意味着您无法控制首先执行代码的流程。我最好的选择是您的全局变量不会改变您的想法。
要解决这个问题,您可以使用meta[] 标签在线程之间交换信息,例如
link = regularListingContainer.xpath('a[contains(@class, "title")]/@href').extract_first()
request=Request(urljoin(link), callback=self.anotherFunc)
request['string']="I'm going on a journy"
yield request
def anotherFunc(self, response)
foo=response['string']
print foo
这将输出
I'm going on a journy
希望对我有所帮助,欢迎进一步提问