在Python中使用BeautifulSoup解析html

在Python中使用BeautifulSoup解析html,python,html,beautifulsoup,Python,Html,Beautifulsoup,我编写了一些代码来解析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()

我编写了一些代码来解析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>"
导入urllib2
html=urllib2.urlopen('http://dummy)。读()
从BeautifulSoup导入BeautifulSoup
soup=BeautifulSoup(html)
对于soup.findAll('span',{class:'d'})中的定义:
definition=definition.renderContents()
打印“”,定义
例如,在soup.find中使用('span',{“class”:'x'}):
打印“”,例如使用“”
打印“”
当class属性为“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>
通过将多个金额相加计算得出
平均利率
以100 km/h的平均速度行驶
典型还是正常
一般智力
晚餐平均20英镑
那么,这就是我想要的结果:

<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>
通过将多个金额相加计算得出
平均利率
以100 km/h的平均速度行驶
典型还是正常
一般智力
晚餐平均20英镑

是的,您可以获取html中的所有跨距,然后每次检查一个“d”或“x”类,如果是,则打印它们

类似的方法可能会奏效(未经测试):

用于汤中的span.findAll('span'):
如果span.find(“span”,“d”).string:
打印“”+span.find(“span”、“d”).string+“”
elif span.find(“span”,“x”)。字符串:
打印“”+span.find(“span”、“x”).string+“”
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>"