python - 在 SCRAPY 中形成 XPATH 选择器

标签 python css scrapy

尝试从页面中提取产品名称:

https://www.v12outdoor.com/view-by-category/rock-climbing-gear/rock-climbing-shoes/mens.html

找不到返回有用的特定结果的 XPATH。

很抱歉我的第一篇文章是这样一个初学者问题:(

class V12Spider(scrapy.Spider):
name = 'v12'
start_urls = ['https://www.v12outdoor.com/view-by-category/rock-climbing-gear/rock-climbing-shoes/mens.html']


def parse(self, response):
    yield {
        'price' : response.xpath('//span[@id="product-price-26901"]/text()'),
        'name' : response.xpath('//h3[@class="product-name"]/a/text()'),
           }

对于 name,我希望从 h3 标签中带有类 product-name 的元素中生成名称,但会生成多行数据='\r\n

(虽然我们是为了price,但有没有办法只提取数值?)

最佳答案

您面临的问题可以通过对 xpath 使用 get() 方法然后对字符串使用 strip() 方法来解决。 我试过这样的事情

name= response.xpath('//h3[@class="product-name"]/a/text()').get()

给予

'\r\n                                RED CHILLI VOLTAGE                            '

然后使用

name.strip()

给予

'RED CHILLI VOLTAGE'

所以你可以用

替换你的名字声明
name= response.xpath('//h3[@class="product-name"]/a/text()').get().strip()

获取价格的相同解决方案,只需在语句末尾添加 .get().strip

希望这对您有所帮助。 另请阅读 https://docs.scrapy.org/en/latest/topics/selectors.html 中的 .getall() 方法。

关于python - 在 SCRAPY 中形成 XPATH 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57769980/

相关文章:

支持查询的CSS预处理器

javascript - jQuery:定位一个div以用溢出填充容器div的可见部分

python - Scrapy - 在抓取期间写入磁盘

python - Scrapy Middleware 忽略 URL 并防止抓取

python - 让 Scrapy 跟随链接并收集数据

python - 当在 csv 中提取坐标和帧数时,如何在视频上绘制边界框?

python - 有没有更简洁的方法来测试 python3 中的长参数列表?

python - tkk : custom style doesn't work

python - 为什么 `dataclasses.asdict(obj)` > 10x 比 `obj.__dict__()` 慢

javascript - 创建推送动画