scrapy(python)中的无效xpath

你好我正在尝试使用 scrapy 构建一个爬虫我的爬虫代码是:


import scrapy

from shop.items import ShopItem



class ShopspiderSpider(scrapy.Spider):

    name = 'shopspider'

    allowed_domains = ['www.organics.com']

    start_urls = ['https://www.organics.com/product-tag/special-offers/']




    def parse(self, response):

      items = ShopItem()

      title = response.xpath('//*[@id="content"]/div[2]/div[1]/ul/li[1]/a/h3').extract()

      sale_price = response.xpath('//*[@id="content"]/div[2]/div[1]/ul/li[1]/a/span[2]/del/span').extract()

      product_original_price = response.xpath('//*[@id="content"]/div[2]/div[1]/ul/li[1]/a/span[2]/ins/span').extract()

      category = response.xpath('//*[@id="content"]/div[2]/div[1]/ul/li[1]/a/span[2]/ins/span').extract()


      items['product_name'] = ''.join(title).strip()

      items['product_sale_price'] = ''.join(sale_price).strip()

      items['product_original_price'] = ''.join(product_original_price).strip()

      items['product_category'] = ','.join(map(lambda x: x.strip(), category)).strip()

      yield items



但是当我运行命令: scrapy crawl shopspider -o info.csv

以查看输出时,我只能找到有关第一个产品的信息,而不是此页面中的所有产品。

所以我删除了 xpath 中 [ ] 之间的数字,例如标题的 xpath ://*[@id="content"]/div/div/ul/li/a/h3 但仍然得到相同的结果

结果是:<span class="amount">£40.00</span>,<h3>Halo Skincare Organic Gift Set</h3>,"<span class=""amount"">£40.00</span>","<span class=""amount"">£58.00</span>"

请帮忙


慕工程0101907
浏览 136回答 1
1回答

Smart猫小萌

如果您删除 XPath 上的索引,它们将找到页面中的所有项目:response.xpath('//*[@id="content"]/div/div/ul/li/a/h3').extract() # Returns 7 items但是,您应该注意到这将返回所选 html 元素的字符串列表。如果您想要元素内的文本,您应该添加/text()XPath。(这看起来像你做的)另外,你只得到一个回报的原因是因为你在将所有项目分配给时将它们连接成一个字符串item:items['product_name'] = ''.join(title).strip()这title是一个元素列表,您将它们全部连接在一个字符串中。相同的逻辑适用于其他变量如果那真的是您想要的,您可以忽略以下内容,但我相信更好的方法是分别执行 for 循环和yield它们?我的建议是:def parse(self, response):&nbsp; products = response.xpath('//*[@id="content"]/div/div/ul/li')&nbsp; for product in products:&nbsp; &nbsp; &nbsp; items = ShopItem()&nbsp; &nbsp; &nbsp; items['product_name'] = product.xpath('a/h3/text()').get()&nbsp; &nbsp; &nbsp; items['product_sale_price'] = product.xpath('a/span/del/span/text()').get()&nbsp; &nbsp; &nbsp; items['product_original_price'] = product.xpath('a/span/ins/span/text()').get()&nbsp; &nbsp; &nbsp; items['product_category'] = product.xpath('a/span/ins/span/text()').get()&nbsp; &nbsp; &nbsp; yield items请注意,在您的原始代码中,您的categoryvar 与您的 具有相同的 XPath product_original_price,我将逻辑保留在代码中,但这可能是一个错误。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python