Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何捕获HTML,不受捕获库的干扰?_Python_Html_Web Scraping_Beautifulsoup_Lxml - Fatal编程技术网

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

Python 如何捕获HTML,不受捕获库的干扰?,python,html,web-scraping,beautifulsoup,lxml,Python,Html,Web Scraping,Beautifulsoup,Lxml,有没有一个Python库可以让我在不干扰标记的情况下获取任意HTML片段?据我所知,lxml、BeautifulSoup和pyquery都使类似于soup.find(“.arbitral class”)的东西变得容易,但它返回的HTML是格式化的。我想要原始的原始标记 例如,假设我有: <html> <head> <title>test</title> </head> <body> <div

有没有一个Python库可以让我在不干扰标记的情况下获取任意HTML片段?据我所知,lxml、BeautifulSoup和pyquery都使类似于
soup.find(“.arbitral 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>

测试
这是一些
使用
一些潜在的问题

里面的东西
我想准确地捕捉到:

”
这是一些
使用
一些潜在的问题

里面的东西 "
…空格和所有空格,并且不会损坏要正确格式化的标记(例如

麻烦的是,这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']
此代码的输出如下所示:

'\n    This is some<br />\n    markup with <br>\n    <p>some potentially problematic</p>\n    stuff in it <input type="text" name="w00t">'
”\n这是一些
\n标记,其中包含一些可能有问题的内容

请注意,第一个

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

但这修改了标记。请注意,第一个

缺少空格,
标签在结束前添加了一个
/
@Daniel如果您对编辑的版本满意,请将我的答案标记为已接受。谢谢
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">'