Scrapy无法获得所有价格

2024-05-29 08:18:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用scrapy来爬行this page

class QuotesSpider(scrapy.Spider):
    name = "tesco"
    start_urls = [
        'https://www.tesco.com/direct/tv-offer.event?icid=offers_trade_slot1',
    ]

    def parse(self, response):
        for quote in response.xpath('//li[contains(@class,"product-tile")]'):
            learningscrapyItem = crawlerItem()
            learningscrapyItem['title'] = quote.xpath('.//h3/a/text()').extract_first()
            price = quote.xpath('.//div[@class="buy-box-container"]/p[2]/text()').extract_first()
            learningscrapyItem['price'] = price.strip()
            yield (learningscrapyItem)

我对xpath的价格有意见,这只会影响一些价格:

//div[@class="buy-box-container"]/p[2]/text()

通过删除text(),我想我可以理解为什么,那些拉动价格的设置如下所示:

<p class="price">
£189.00
</p>

非结构化的结构如下:

<p class="price">

<span class="from">From</span>
£549.00
</p>

所以strip()似乎正在移除这些。Xpath有没有一种方法可以让我从paragraph标记中获取文本,而不是从/或其中的span中获取文本?你知道吗

谢谢。你知道吗


Tags: textdivresponseextract价格buypricexpath
2条回答

问题是/text()只会匹配直接文本子节点,而且,您正确地理解了,第二个示例破坏了选择器。你知道吗

我只需要从“price”元素中获取所有的“text”节点,然后用.re_first()获取数量:

price = quote.xpath('.//div[@class="buy-box-container"]/p[2]//text()').re_first(r"\d+\.\d+")

或者,使用CSS选择器而不是XPath更简单:

price = quote.css('.buy-box-container .price').re_first(r"\d+\.\d+")

试试下面的方法来获得你想要的价格。你知道吗

而不是用这个:

quote.xpath('.//div[@class="buy-box-container"]/p[2]/text()').extract_first()

尝试使用以下选项:

quote.xpath('.//div[@class="buy-box-container"]//p[@class="price"]/text()').extract()[-1]

相关问题 更多 >

    热门问题