【发布时间】:2011-10-28 04:09:48
【问题描述】:
【问题讨论】:
标签: python html-parsing
【问题讨论】:
标签: python html-parsing
下面是一个使用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
【讨论】:
上面 cmets 中的链接中提供的 htmlparser 可能是更健壮的方法。但是,如果您在特定标签之间有一些简单的内容,您可以使用regular expressions
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'
【讨论】:
>,它将失败。对于任何不切实际的简单示例,正则表达式是不够的。另见stackoverflow.com/questions/1732348/…