【问题标题】:Can't extract the result as expected when using requests_html使用 requests_html 时无法按预期提取结果
【发布时间】:2019-03-12 23:01:24
【问题描述】:

我无法使用 requests_html 提取正确的结果:

>>> from requests_html import HTMLSession
>>> session = HTMLSession()
>>> r = session.get('https://www.amazon.com/dp/B07569DYGN')
>>> r.html.find("#productDetails_detailBullets_sections1")
[]

我可以在源内容中找到id'productDetails_detailBullets_sections1':

>>> """<table id="productDetails_detailBullets_sections1" class="a-keyvalue prodDetTable" role="presentation">""" in r.text
True

其实这个问题在 PyQuery 中也同样存在。

为什么requests_html 找不到这个元素?

【问题讨论】:

  • 我可以确认源包含&lt;table id="productDetails_detailBullets_sections1" ...,而.find 返回一个空数组。
  • r.html.find('table') 也没有找到那个对象,似乎PQuery() 对这里的某些事情不满意。
  • @MartijnPieters 是的,它只提取了四个表。
  • PQuery 库只是将 CSS 选择器转换为有效的 "descendant-or-self::*[@id = 'productDetails_detailBullets_sections1'] XPath 表达式。所以这现在归结为 lxml; r.html.pq[0].xpath("descendant-or-self::table") 确实只返回 4 个元素。
  • PyQuery(r.html.html, parser='html5')('#productDetails_detailBullets_sections1') 找到元素。

标签: python python-3.x pyquery python-requests-html


【解决方案1】:

我正在搜索#comparison_price_row,它仍然可以找到一些东西。源中的下一个 id 是 comparison_shipping_info_row 但搜索 #comparison_shipping_info_row 会返回一个空数组。这两个元素位于同一级别(同一父级)。我检查了两者之间的所有来源,但没有发现问题。

一开始。

然后我看到两者之间的某个地方有一个 NUL 字节,这可能会使库绊倒。

从输入中删除 NUL 字节后,可以找到想要的元素:

r2 = requests_html.HTML(html=r.text.replace('\0', ''))
r2.find('#productDetails_detailBullets_sections1')

[<Element 'table' role='presentation' class=('a-keyvalue', 'prodDetTable') id='productDetails_detailBullets_sections1'>]

【讨论】:

  • 很好的发现。如果我正确阅读了规范,html 文档中的空字符应该会导致解析错误。 w3.org/TR/html51/syntax.html#rcdata-state。所以这个错误是亚马逊的,而不是 lxml 解析器。
  • 是的,好吧,我们都知道当今典型 HTML 的错误率有多高 ;-) 所以问题始终是:尽管存在错误,但解析器在弄清楚其含义方面有多好.我猜,忽略 NUL 字节是更简单的任务之一。
  • @Alfe 干得好,但这不能从基础上解决问题,只对这个有用,剂量吗? :(感谢您的出色工作。
  • @ZhaoyangXu 问题有两个方面:①服务器返回带有NUL的HTML(它不应该)和②解析器在NUL处中止(这只是因为①而令人讨厌)。最重要的是了解正在发生的事情,以便更好地预测类似问题及其症状。另一件事是解决手头的具体问题。当然,它并不能解决所有类似的问题(比如损坏的 HTML 或类似问题),但至少可以解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 2022-06-11
  • 2021-06-27
  • 1970-01-01
相关资源
最近更新 更多