[英]Scrapy request does not callback
我正在嘗試創建一個蜘蛛,從csv(兩個鏈接,每行一個名稱)獲取數據,並從每個鏈接中抓取一個簡單元素(價格),為每一行返回一個項目,項目的名稱為CSV中的名稱,以及兩個報廢價格(每個鏈接一個)。
一切都按預期進行,除了事實是不返回價格,而是從每個請求的回調函數返回價格,我得到了一個請求對象,如下所示:
<獲取https://link.com > ..
根本不調用回調函數,為什么呢?
這是蜘蛛:
f = open('data.csv')
f_reader = csv.reader(f)
f_data = list(f_reader)
parsed_data = []
for product in f_data:
product = product[0].split(';')
parsed_data.append(product)
f.close()
class ProductSpider(scrapy.Spider):
name = 'products'
allowed_domains = ['domain1', 'domain2']
start_urls = ["domain1_but_its_fairly_useless"]
def parse(self, response):
global parsed_data
for product in parsed_data:
item = Product()
item['name'] = product[0]
item['first_price'] = scrapy.Request(product[1], callback=self.parse_first)
item['second_price'] = scrapy.Request(product[2], callback=self.parse_second)
yield item
def parse_first(self, response):
digits = response.css('.price_info .price span').extract()
decimals = response.css('.price_info .price .price_demicals').extract()
yield float(str(digits)+'.'+str(decimals))
def parse_second(self, response):
digits = response.css('.lr-prod-pricebox-price .lr-prod-pricebox-price-primary span[itemprop="price"]').extract()
yield digits
在此先感謝您的幫助!
TL; DR:您應該在產生項目或請求時產生其中帶有Request對象的項目。
長版:
蜘蛛中的解析方法應該返回scrapy.Item
在這種情況下,該爬網的鏈將停止並且scrapy將放置一個項目或scrapy.Requests
在這種情況下,scrady將安排一個請求以繼續鏈。
Scrapy是異步的,因此從多個請求中創建一個項目意味着您需要將所有這些請求鏈接在一起,同時將項目攜帶到每個項目中並一點一點地填滿。 Request對象具有meta
屬性,您可以在其中存儲想要存儲的任何內容(幾乎可以存儲),並將其攜帶到回調函數中。 通常,使用它來鏈接需要多個請求以形成單個項目的項目的請求。
您的蜘蛛應如下所示:
class ProductSpider(scrapy.Spider):
# <...>
def parse(self, response):
for product in parsed_data:
item = Product()
item['name'] = product[0]
# carry next url you want to crawl in meta
# and carry your item in meta
yield Request(product[1], self.parse_first,
meta={"product3": product[2], "item":item})
def parse_first(self, response):
# retrieve your item that you made in parse() func
item = response.meta['item']
# fill it up
digits = response.css('.price_info .price span').extract()
decimals = response.css('.price_info .price .price_demicals').extract()
item['first_price'] = float(str(digits)+'.'+str(decimals))
# retrieve next url from meta
# carry over your item to the next url
yield Request(response.meta['product3'], self.parse_second,
meta={"item":item})
def parse_second(self, response):
# again, retrieve your item
item = response.meta['item']
# fill it up
digits = response.css('.lr-prod-pricebox-price .lr-prod-pricebox-price-primary
span[itemprop="price"]').extract()
item['secodn_price'] = digits
# and finally return the item after 3 requests!
yield item
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.