尝试从页面中提取产品名称:
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/