如何用Python解析HTML文件并获取标签之间的文本?
可能是重复的问题:
在Python中解析HTML
我在网上搜索了很多,想用Python获取标签之间的文本。你们能帮我解释一下吗?
2 个回答
-1
上面评论里提到的htmlparser可能是更可靠的选择。不过,如果你只需要处理一些简单的内容,而且这些内容是在特定的标签之间,你可以使用正则表达式。
import re
html = '<html><body><div id='blah-content'>Blah</div><div id='content-i-want'>good stuff</div></body></html>'
m = re.match(r'.*<div.*id=\'content-i-want\'.*>(.*?)</div>', html)
if m:
print m.group(1) # Should print 'good stuff'
2
这里有一个使用BeautifulSoup来解析HTML的例子:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup("""<html><body>
<div id="a" class="c1">
We want to get this
</div>
<div id="b">
We don't want to get this
</div></body></html>""")
print soup('div', id='a').text
这段代码的输出结果是
We want to get this