使用Python中的BeautifulSoup解析HTML

3
我写了一些代码来解析HTML,但结果并不是我想要的:
import urllib2
html = urllib2.urlopen('http://dummy').read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for definition in soup.findAll('span', {"class":'d'}):
definition = definition.renderContents()
print "<meaning>", definition
for exampleofuse in soup.find('span',{"class":'x'}):
    print "<exampleofuse>", exampleofuse, "<exampleofuse>"
print "<meaning>"

是否有一种方法,可以在类属性为“d”或“x”时获取字符串?

以下HTML代码是我想要解析的:

<span class="d">calculated by adding several amounts together</span>
<span class="x">an average rate</span>
<span class="x">at an average speed of 100 km/h</span>
<span class="d">typical or normal</span>
<span class="x">average intelligence</span>
<span class="x">20 pounds for dinner is average</span>

然后,这是我想要的结果:
<definition>calculated by adding several amounts together
    <example_of_use>an average rate</example_of_use>
    <example_of_use>at an average speed of 100 km/h</example_of_use>
</definition>
<definition>typical or normal
    <example_of_use>average intelligence</example_of_use>
    <example_of_use>20 pounds for dinner is average</example_of_use>
</definition>
1个回答

5

是的,您可以获取html中的所有span元素,然后对每个元素检查其是否包含"d"或"x"类,如果有,则打印输出。

以下示例代码可能有效(未经过测试):

for span in soup.findAll('span'):
    if span.find("span","d").string:
        print "<definition>" + span.find("span","d").string + "</definition>"
    elif span.find("span","x").string:
        print "<example>" + span.find("span","x").string + "</example>"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接