如何在 Scrapy 中使用全局变量解析响应?
How do I parse a response using a global variable in Scrapy?
我将 start_requets 方法修改为:
def start_requests(self):
array = list(open("file", 'r'))
for i in array:
yield self.make_requests_from_url("http://example.org/test.php?id=" + i)
如何在 parse 方法中访问 i 的值?
我尝试设置一个全局变量 idd 并添加
global idd
idd = i
在start_requests方法中然后
def parse(self, response):
item = DataItem()
item['id'] = idd
但是所有项目的 id 字段都填充了 idd 的最后一个值。
我该如何解决这个问题?
一个(可能也是最简单的)选项是将其传递到内部 meta
:
yield scrapy.Request("http://example.org/test.php?id=" + i,
meta={"index": i},
dont_filter=True)
然后,在parse()
中阅读:
def parse(self, response):
index = response.meta["index"]
我将 start_requets 方法修改为:
def start_requests(self):
array = list(open("file", 'r'))
for i in array:
yield self.make_requests_from_url("http://example.org/test.php?id=" + i)
如何在 parse 方法中访问 i 的值?
我尝试设置一个全局变量 idd 并添加
global idd
idd = i
在start_requests方法中然后
def parse(self, response):
item = DataItem()
item['id'] = idd
但是所有项目的 id 字段都填充了 idd 的最后一个值。
我该如何解决这个问题?
一个(可能也是最简单的)选项是将其传递到内部 meta
:
yield scrapy.Request("http://example.org/test.php?id=" + i,
meta={"index": i},
dont_filter=True)
然后,在parse()
中阅读:
def parse(self, response):
index = response.meta["index"]