首页 > 解决方案 > 从格式不同的字段中提取数据的最佳 XPath 实践

问题描述

我正在使用 Python 3.8、XPath 和 Scrapy,这些东西似乎都能正常工作。我认为我的 XPath 表达式是理所当然的。

现在我必须使用 Python 3.8、XPath 和 lxml.html 并且事情变得不那么宽容了。例如,使用这个URL和这个 XPath:

//dt[text()='Services/Products']/following-sibling::dd[1]

我会根据 innerhtml 的内容返回一个段落或一个列表。这就是我现在尝试提取文本的方式:

data = response.text
tree = html.fromstring(data)
Services_Product = tree.xpath("//dt[text()='Services/Products']/following-sibling::dd[1]")

它返回这个: Services_Product[] 这是他页面的“li”元素列表,但其他时候这个字段可以是以下任何一个:

<dd>some text</dd>
or
<dd><p>some text</p></dd>
or
<dd>
  <ul>
    <li>some text</li>
    <li>some text</li>
  </ul>
</dd>
or
<dd>
  <ul>
    <li><p>some text</p></li>
    <li><p>some text</p></li>
  </ul>
</dd>

从目标字段可以是许多不同事物的情况中提取文本的最佳实践是什么?

我使用此测试代码来查看我的选项是什么:

file = open('html_01.txt', 'r')
data = file.read()
tree = html.fromstring(data)
Services_Product = tree.xpath("//dt[text()='Services/Products']/following-sibling::dd[1]")
stuff = Services_Product[0].xpath("//li")
for elem in stuff:
    print(elem[0][0].text)

这返回了: 健康 健康医生 健康医生

这是不正确的。这是谷歌浏览器中的截图:谷歌 浏览器中的 Xpath 工具以及有问题的 html

使用 Python 和 Xpath 或其他选项抓取这些数据的最佳方法是什么?谢谢你。

标签: pythonxpathlxml.html

解决方案


在花了几个小时谷歌搜索然后在上面写了这篇文章之后,我突然想到了:旧代码:

Services_Product = tree.xpath("//dt[text()='Services/Products']/following-sibling::dd[1]")
stuff = Services_Product[0].xpath("//li")

以及返回漂亮文本列表的新代码:

Services_Product = tree.xpath("//dt[text()='Services/Products']/following-sibling::dd[1]")
stuff = Services_Product[0].xpath("//li/text()")

在末尾添加“/ text()”修复它。


推荐阅读