试图从包含历史产品数据的www.archive.org
中抓取信息。我下面的代码尝试单击列出的每个产品,scrape
每个产品的信息,并对后续页面执行相同的操作。
问题是它跳过了一些产品(特别是20个),即使xpath:
products = response.xpath("//article[contains(@class,'product result-prd')]")
对所有产品都是一样的。请看我下面的完整代码。
class CurrysSpider(scrapy.Spider):
name = 'currys_mobiles_2015'
#allowed_domains = ['www.currys.co.uk']
start_urls = ['https://web.archive.org/web/20151204170941/http://www.currys.co.uk/gbuk/phones-broadband-and-sat-nav/mobile-phones-and-accessories/mobile-phones/362_3412_32041_xx_xx/xx-criteria.html']
def parse(self, response):
products = response.xpath("//article[contains(@class,'product result-prd')]") # done
for product in products:
brand = product.xpath(".//span[@data-product='brand']/text()").get() # done
link = product.xpath(".//div[@class='productListImage']/a/@href").get() # done
price = product.xpath(".//strong[@class='price']/text()").get().strip() # done
description = product.xpath(".//ul[@class='productDescription']/li/text()").getall() # done
absolute_url = link # done
yield scrapy.Request(url=absolute_url,callback=self.parse_product,
meta={'brand_name':brand,
'product_price':price,
'product_description':description}) # done
# process next page
next_page_url = response.xpath("//ul[@class='pagination']//li[last()]//@href").get()
absolute_next_page_url = next_page_url
if next_page_url:
yield scrapy.Request(url=absolute_next_page_url,callback=self.parse)
def parse_product(self, response):
.....
希望您能就此提供一些反馈。
发布于 2020-11-30 15:06:01
尝试查看这些产品是否存在于页面html中或通过js加载。只需使用ctrl+U并检查这些产品的html body即可。
发布于 2020-11-30 22:27:35
可能是由于JS加载的原因,单个页面没有正确加载,因为其余代码看起来没有问题(尽管我建议使用normalize-space($xpath)
而不是.strip()
)。
为了测试这一点(在Chrome上),访问你的目标网页,打开Chrome Dev Tools(F12),点击"Console“和Ctrl+Shift+P弹出命令窗口。
接下来,键入“禁用Javascript”,并在出现时选择该选项。现在,使用Ctrl+R来刷新页面,这就是你的web抓取器得到的“视图”。现在检查您的Xpath表达式。
如果您确实有问题,请考虑使用scrapy-splash或scrapy-selenium来加载此JS。
编辑:我会检查内存泄漏的可能性。根据scrapy docs的说法,在回调中使用meta属性有时会导致泄漏。
https://stackoverflow.com/questions/65073750
复制相似问题