繁体   English   中英

使用Python中的BeautifulSoup解析html

[英]Parsing html using BeautifulSoup in Python

我写了一些代码来解析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>"

当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>

然后,这是我想要的结果:

<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>

是的,你可以获得html中的所有跨度,然后每次检查一个“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>"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM