标准库附带了各种结构化标记处理工具,您可以使用它来解析 HTML,然后搜索它以提取您的 div。
那里有很多选择。你用什么?
html.parser看起来是显而易见的选择,但我实际上会从ElementTree反而。它是一个非常好的、非常强大的 API,网络上有大量的文档和示例代码可以帮助您入门,并且有很多专家每天使用它来帮助您解决问题。如果事实证明 etree 无法解析您的 HTML,您将不得不使用其他东西......但首先尝试一下。
例如,通过对 HTML 片段进行一些小修复,使其实际上有效,因此实际上有一些文本值得从您的 div 中删除:
<html>
<head>...</head>
<body>
*lots of other <div /> tags*
<div class = "want" style="font-family:verdana;font-size:12px;letter-spacing:normal">spam spam spam
<form class ="subform">...</form>
<div class = "subdiv1" >...</div>
<div class = "subdiv2" >...</div>
*lots of other <div /> tags*
</div>
</body>
</html>
您可以使用这样的代码(我假设您知道或愿意学习 XPath):
tree = ElementTree.fromstring(page)
mydiv = tree.find('.//div[@class="want"]')
现在您已经获得了对div
与类"want"
。您可以通过以下方式获取其直接文本:
print(mydiv.text)
但如果你想提取整个子树,那就更容易了:
data = ElementTree.tostring(mydiv)
如果你想把它包装在一个有效的<html>
and <body>
和/或删除<div>
本身,您必须手动完成该部分。该文档解释了如何使用简单的树 API 构建元素:您创建一个head
and a body
放入html
,然后粘上div
in the body
, then tostring
the html
,就是这样。