在Python中使用BeautifulSoup解析html [英] Parsing html using BeautifulSoup in Python

查看:120
本文介绍了在Python中使用BeautifulSoup解析html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些代码来解析html,但是结果却不是我想要的:

I wrote some code to parse html, but the result was not what I wanted:

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"时,是否可以通过某种方式获取字符串?

Is there any kind of way that when class attribute is "d" or "x" to then get the string?

以下html代码是我要解析的内容:

The following html code is what I want to parse:

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

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

Then, this is the result I want:

<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"类的对象进行检查,如果可以, ,打印出来.

yes, you can get all of the spans in the html, then for each check for a class of "d" or "x", and if they do, print them.

类似的事情可能会起作用(未经测试):

something like this might work (untested):

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

这篇关于在Python中使用BeautifulSoup解析html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆