在Python中使用BeautifulSoup解析html
我写了一些代码来解析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>
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>"
Is there any kind of way that when class attribute is "d" or "x" to then get the string?
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以获取 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):