【问题标题】:lxml.html does not find body taglxml.html 找不到正文标记
【发布时间】:2019-10-11 03:48:56
【问题描述】:

我使用 lxml.html 来解析各种 html 页面。现在我认识到,至少对于某些页面,尽管它存在并且漂亮的汤找到了它(即使它使用 lxml 作为解析器),但它没有找到 body 标签。

示例页面:https://plus.google.com/(剩下的部分)

import lxml.html
import bs4

html_string = """
    ... source code of https://plus.google.com/ (manually copied) ...
"""

# lxml fails (body is None)
body = lxml.html.fromstring(html_string).find('body')

# Beautiful soup using lxml parser succeeds
body = bs4.BeautifulSoup(html_string, 'lxml').find('body')

欢迎对这里发生的事情进行任何猜测 :)

更新:

问题似乎与编码有关。

# working version
body = lxml.html.document_fromstring(html_string.encode('unicode-escape')).find('body')

【问题讨论】:

  • 你的html_string是什么?
  • @JackFleeting 它的plus.google.com 的内容。我没有添加它,因为它很大。

标签: python beautifulsoup lxml


【解决方案1】:

你可以这样使用:

import requests
import lxml.html

html_string = requests.get("https://plus.google.com/").content
body = lxml.html.document_fromstring(html_string).find('body')

body 变量包含 body html 元素

【讨论】:

  • 非常有趣。您的代码似乎可以工作,但它似乎与我之前所做的相当。不同之处似乎在于您使用的是编码内容,而我使用的是手动复制的源代码。我会调查的,TY!
  • 我看到的主要区别是 html 标记及其内容是通过执行各种 javascript 生成的
  • body 标签必须是硬编码的,否则我们的代码都不起作用,不是吗?我仔细查看了源代码,发现了一些十六进制编码字符(例如 \x3d)看起来它们破坏了 lxml 而漂亮的汤可以处理它。
猜你喜欢
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-12
相关资源
最近更新 更多