python - 如何捕获 HTML,不受捕获库的干扰?

标签 python html web-scraping beautifulsoup lxml

是否有一个 Python 库可以让我在不干扰标记的情况下获得任意 HTML 片段?据我所知,lxml、BeautifulSoup 和 pyquery 都可以轻松实现类似 soup.find(".arbitrary-class") 的功能。 ,但它返回的 HTML 是经过格式化的。我想要原始的原始标记。

例如,假设我有这个:

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <div class="arbitrary-class">
      This is some<br />
      markup with <br>
      <p>some potentially problematic</p>
      stuff in it <input type="text" name="w00t">
    </div>
  </body>
</html>

我想准确捕捉:

"
      This is some<br />
      markup with <br>
      <p>some potentially problematic</p>
      stuff in it <input type="text" name="w00t">
    "

...空格等等,并且不会破坏标签的正确格式(例如 <br />)。

问题似乎在于,所有 3 个库似乎都在内部构建 DOM,并且只是返回一个代表文件应该的 Python 对象,而不是它是什么 ,所以我不知道在哪里/如何获取我需要的原始代码片段。

最佳答案

这段代码:

from bs4 import BeautifulSoup
with open("index.html") as fp:
    soup = BeautifulSoup(fp, "html.parser")
    print soup.select(".arbitrary-class")[0].contents

将返回给您列表:

[u'\n      This is some', <br/>, u'\n      markup with ', <br/>, u'\n', <p>some potentially problematic</p>, u'\n      stuff in it ', <input name="w00t" type="text"/>, u'\n']

编辑:

正如丹尼尔在评论中指出的,这会导致标准化标签。

我能找到的唯一替代方法是使用解析器生成器,例如 pyparsing。下面的代码是对他们的一些example code稍作修改对于withAttribute功能。

from pyparsing import *

html = """<html>
<head>
    <title>test</title>
</head>
<body>
    <div class="arbitrary-class">
    This is some<br />
    markup with <br>
    <p>some potentially problematic</p>
    stuff in it <input type="text" name="w00t">
    </div>
</body>
</html>"""

div,div_end = makeHTMLTags("div")

# only match div tag having a class attribute with value "arbitrary-class"
div_grid = div().setParseAction(withClass("arbitrary-class"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.searchString(html):
    print repr(grid_header.body)

此代码的输出如下:

'\n    This is some<br />\n    markup with <br>\n    <p>some potentially problematic</p>\n    stuff in it <input type="text" name="w00t">'

请注意第一个 <br/>现在有一个空间,并且 <input>标签不再在结束 > 之前添加/。与您的规范的唯一区别是缺少尾随空格。您也许可以通过改进此解决方案来解决此差异。

关于python - 如何捕获 HTML,不受捕获库的干扰?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50855442/

相关文章:

python - 在同一张图中结合mayavi和matplotlib

html - 用于隐藏文本的 CSS 选择器

python - 从 Mega.nz 文件中抓取文本 (Python)

python - lxml xpath 找不到 anchor 文本

python - 检查seaborn散点图函数是否正在采样数据

php - 如何将 PHP 对象传递给 Python,反之亦然

javascript - 通过单击第一个 div 设置第二个 div 的名称

html - 自动图像调整大小编码 html/css

web-scraping - 如何使用splash获取弹出内容

python - 如何设置起始索引未知的范围