使用Scrapy从div选择器中提取文本

时间:2019-05-18 18:06:01

标签: python scrapy

我正在尝试获取价格文本 potterybarn位于刮板外壳中。我使用了scrapy shell "https://www.potterybarnkids.com/shop/easter/easter-shop-all-baskets/",然后尝试获取跨度class="price-state price-sale"内的价格,有没有办法进入跨度内的每个跨度来提取跨度内的整个文本?

我尝试了

response.xpath('//span[@class="price-state price-sale"]/text()').extract()response.xpath('//span[@class="price-state price-sale"]//text()')[0].extract()

我需要一种方法来提取选择器内的所有文本,因为它具有内部跨度,div,...

我在此示例中选中了How can i extract only text in scrapy selector in python,也选中了Scrapy extracting text from div,答案是假定它仅包含在该示例和该示例中都可以使用的span子级。但是由于//text()无法正常工作,有没有更通用的方法可以正确提取子级中的所有文本。

1 个答案:

答案 0 :(得分:0)

我认为有更有效的方法,但是下面的xpath是有效的。 xpath上的string()从所有子节点收集文本。

您可以在此Difference between text() and string()上找到有关string()text()之间差异的更多信息

prices = [
    r.xpath('string(.)').extract_first() 
    for r in response.xpath('//span[@class="price-state price-sale"]')
]

如您在结果中看到的,每行一种产品。例如,可以使用replace进行清理,或使用regex

提取价格
>>> prices
['\n\nSale\n\n\n$5.99\n–\n\n$18.99\n', '\n\nSale\n\n\n$6...

其他选择是分两步进行操作,使用text()代替string()并在join操作之前清除数据:

>>> prices = []
>>> for r in response.xpath('//span[@class="price-state price-sale"]'):
>>>     price = [p.strip() for p in r.xpath('.//text()').extract() if p.strip()]
>>>     prices.append(' '.join(price))

这种情况下的结果已经清除

>>> prices
['Sale $ 5.99 – $ 18.99', 'Sale $ 6.99 – $ 18.99', 'Sale $ 6.99...
相关问题