我需要匹配所有这些开始标记:
<p>
<a href="foo">
Run Code Online (Sandbox Code Playgroud)
但不是这些:
<br />
<hr class="foo" />
Run Code Online (Sandbox Code Playgroud)
我想出了这个,并希望确保我做对了.我只抓住了a-z.
<([a-z]+) *[^/]*?>
Run Code Online (Sandbox Code Playgroud)
我相信它说:
/,然后我有这个权利吗?更重要的是,你怎么看?
我正在使用lxml.html编写一个脚本来解析网页.我在我的时间里做了很多BeautifulSoup,但由于它的速度,我现在正在尝试lxml.
我想知道库中最明智的方法是做相当于Javascript的InnerHtml - 即检索或设置标签的完整内容.
<body>
<h1>A title</h1>
<p>Some text</p>
</body>
Run Code Online (Sandbox Code Playgroud)
因此InnerHtml是:
<h1>A title</h1>
<p>Some text</p>
Run Code Online (Sandbox Code Playgroud)
我可以使用黑客(转换为字符串/正则表达式等)来做到这一点,但我假设有一个正确的方法来使用由于不熟悉我缺少的库.谢谢你的帮助.
编辑:感谢pobk如此快速有效地向我展示了这方面的方法.对于任何尝试相同的人,这是我最终得到的:
from lxml import html
from cStringIO import StringIO
t = html.parse(StringIO(
"""<body>
<h1>A title</h1>
<p>Some text</p>
Untagged text
<p>
Unclosed p tag
</body>"""))
root = t.getroot()
body = root.body
print (element.text or '') + ''.join([html.tostring(child) for child in body.iterdescendants()])
Run Code Online (Sandbox Code Playgroud)
请注意,lxml.html解析器将修复未关闭的标记,因此请注意这是否存在问题.