首页 > 解决方案 > 当标签为@href 时,xpath text() 返回“None”

问题描述

我正在尝试提取 HTML 标记中包含的文本以构建 python defaultdict。为此,我需要清除所有 xpath 和/或 HTML 数据并只获取文本,我可以使用 来完成/text()除非它是href

我如何抓取物品:

for item in response.xpath(
    "//*[self::h3 or self::p or self::strong or self::a[@href]]"):

如果我打印上面的内容而不进行提取尝试,它的外观如何:

<Selector xpath='//*[self::h3 or self::p or self::a[@href]]' data='<h3> Some text here ...'>
<Selector xpath='//*[self::h3 or self::p or self::a[@href]]' data='<a href="https://some.url.com...'>

我想提取“Some text here”和“https://some.url.com”

我如何尝试提取文本:

item = item.xpath("./text()").get()
print(item):

结果:

Some text here
None

“无”是我希望看到的:https://some.url.com在尝试了网上建议的各种方法后,我无法让它工作。

标签: xpathscrapy

解决方案


尝试使用这一行来提取文本或@href

item = item.xpath("./text() | ./@href").get()

推荐阅读