使用Python中的BeautifulSoup解析html
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用Python中的BeautifulSoup解析html,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1532字,纯文字阅读大概需要3分钟。
内容图文
![使用Python中的BeautifulSoup解析html](/upload/InfoBanner/zyjiaocheng/719/ac44b75feb3a410bbb06dd670154c38b.jpg)
我写了一些代码来解析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>"
内容总结
以上是互联网集市为您收集整理的使用Python中的BeautifulSoup解析html全部内容,希望文章能够帮你解决使用Python中的BeautifulSoup解析html所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。