我正在尝试抓取一些网站。我已经获得了数据,并尝试使用传递值meta={}
。但是,当我使用yield scrapy.Request
下一个功能时,就会出现问题。我被发送到下一个函数的是一个新的URL,并meta
用于传递JSON值。我有新的URL,但没有JSON数据,JSON从未更新。刚刚传递了相同的值。我不知道是怎么回事。
您可以看到我的代码,我想传递JSON值,但是我只得到了相同的JSON,但URL随新URL一起更新。
def first_function(self, response):
value_json = self.get_json() #i got the json from here
for key, value in value_json.items(): #loop the json
for values in value:
# values will show me as dictionay of dictionary
# thats like {"blabla":{"key1":"value1","key1":"value2"}}
# I gave the conditions as below to get just a value or to make sure if that key ("blabla") is exist
# if the condition is true, i will get the value {"key1":"value1","key1":"value2"}
if values == "blabla":
get_url = "http://www.example.com/"
yield Request(
url=get_url+values["id_url"],
meta={"data_rest":values},
callback=self.second_function
)
def second_function(self, response):
# ============== PROBLEM =====================
# The problem is here!
# I always got a new url from first_function, my logic is if I got a new url, i should get a new json
# but the json or "data_rest" never updated. Always send the same json to this function
# ============== PROBLEM =====================
josn_data = response.meta["data_rest"]
names = response.css() #get the tag in here
for get_data in names:
sub_url = get_data.css("a::attr(href)").extract()
for loop_url_menu in sub_url:
yield scrapy.Request(
url=loop_url_menu,
headers=self.session,
meta = {
'dont_redirect': True,
'handle_httpstatus_list': [302]
}, callback=self.next_function
)
好消息!!我可以解决的 我们只需要在第一个值后附加值,就可以生成该值。
def first_function(self, response):
temp = []
value_json = self.get_json() #i got the json from here
for key, value in value_json.items(): #loop the json
for values in value:
if values == "blabla":
get_url = "http://www.example.com/"
temp.append(values)
yield Request(
url=get_url+values["id_url"],
meta={"data_rest":temp},
callback=self.second_function
)