Python Scrapy:通过另一个函数生成在一个函数中定义的变量名
在parse函数中将一个变量声明为“self.Title”并通过另一个函数生成数据后,它只返回一个URL的数据,而所有其他URL都返回该数据。可能会出现什么问题。下面是代码片段Python Scrapy:通过另一个函数生成在一个函数中定义的变量名,python,scrapy,Python,Scrapy,在parse函数中将一个变量声明为“self.Title”并通过另一个函数生成数据后,它只返回一个URL的数据,而所有其他URL都返回该数据。可能会出现什么问题。下面是代码片段 import scrapy from scrapy.http import Request class TestSpider(scrapy.Spider): name = 'Test' allowed_domains = ['example.com'] start_urls = ['https:
import scrapy
from scrapy.http import Request
class TestSpider(scrapy.Spider):
name = 'Test'
allowed_domains = ['example.com']
start_urls = ['https://example.com/search?q=com.foo', 'https://example.com/search?q=bar', 'https://example.com/search?q=data']
def parse(self, response):
self.Title = response.xpath('//*[@class="search-title"]/a/text()')[0].extract()
Ini_Url = response.xpath('//*[@class="search-title"]/a/@href')[0].extract()
Ab_url = "https://example.com" + Ini_Url + "/download?from=details"
yield Request(Ab_url, callback=self.parse_download)
def parse_download(self, response):
Download_URL = response.xpath('//*[@class="fdownload-box"]/p[2]/a/@href')[0].extract()
yield{"Download_URL": Download_URL, "Title": self.Title}
输出结果就像下载一样,所有3个刮取URL的URL都不同,但标题不同,但所有3个请求的URL都相同。您不能将每个项目的数据存储在Spider类的实例上
当
解析
产生请求
时,将标题
作为元数据
传递,如中所述。然后可以在response.meta
属性的parse\u download
中使用它 作为解决方案,我确实在第一个函数中编写了以下代码片段:
request.meta['Title'] = Title
yield request
并通过以下途径将其调用到另一个:
Title = response.meta['Title']
很抱歉这么晚才回复,但考虑到我是初学者,你能帮我回答这个问题吗。