使用extract_first()时,Scrapy无法获取干净文本

2024-06-17 02:52:01 发布

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

我试图从一个网站刮下许多跨标签的一些文字,但没有得到干净的文字,任何帮助将不胜感激!你知道吗

以下是网址:

https://www.example.com

这就是我要尝试的

response.xpath('//div[@class="agency-header__address"]').extract_first()

预期产量:

Level 18, 25 Bligh Street, SYDNEY, NSW 2000

Tags: httpsdivcom网站addressexampleresponsewww
3条回答

您可以通过提取div字符串表示形式来获取所需的文本:

response.xpath('string(//div[@class="agency-header__address"])').extract_first()

这个任务有一个有用的库(来自Scrapy的创建者),您应该试试:https://github.com/TeamHG-Memex/html-text

import html_text
i_need_text=response.xpath('//div[@class="agency-header__address"]').extract_first()
html_text.extract_text(i_need_text)

出[4]:“新南威尔士州悉尼布莱街25号18楼,2000”

您需要为给定xpath中的所有内容获取xpathtext()。 例如:

result = response.xpath('//div[@class="agency-header__address"]//text()').extract()

这将返回多个span元素,因此必须使用extract()。 然后你可以加入并清洗它,你想,也许像:

''.join(result).replace('\xa0', ' ')

相关问题 更多 >