【问题标题】:Best XPath practices for extracting data from a field that varies in format从格式不同的字段中提取数据的最佳 XPath 实践
【发布时间】:2021-07-23 08:57:39
【问题描述】:

我使用的是 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)

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

这是不正确的。这是它在谷歌浏览器中的屏幕截图: The Xpath tool in google chrome along with the html in question

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

【问题讨论】:

  • 最佳做法是为您提供所需的结果。

标签: python xpath lxml.html


【解决方案1】:

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

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()”修复它。

【讨论】:

    猜你喜欢
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    相关资源
    最近更新 更多