Skip to main content
 首页 » 编程设计

python之Scrapy xpath 删除 字符后的文本

2024年10月24日10yyy_WW

我正在尝试从 this 获取产品信息页。为了获取描述(出现在页面底部),我使用了 xpath

response.xpath('//*[@itemprop="description"]/table//text()').extract()[3].strip() 

这给了我描述:

u'Color: White, Size:Free Size, With the body: Braided, Buckle: Automatic Deduction, With the body width: section (' 

而网站上显示的是

Color: White, Size:Free Size, With the body: Braided, Buckle: Automatic Deduction, With the body width: section (<2cm), Belt Length: 93cm 
Product Type: Belts, Accessories 

我已验证即使在禁用 javascript 后网站上的内容也会加载。我在这里缺少什么?

请您参考如下方法:

这仍然应该在没有任何hack的情况下处理,但您可以使用:

from parsel import Selector 
... 
 
s = Selector(text=response.body_as_unicode(), type='xml') 
s.xpath('//*[@itemprop="description"]/table//text()').extract()[3].strip() 
# gives u'Color: White, Size:Free Size, With the body: Braided, Buckle: Automatic Deduction, With the body width: section (2cm), Belt Length: 93cm' 

这里的问题是 parsel(内部 scrapy 解析器)使用 lxml.etree.HtmlParser(recover=True, encoding='utf8') 删除了这种奇怪的字符以避免出现问题。