使用Python和Beautiful Soup解析HTML
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用Python和Beautiful Soup解析HTML,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1956字,纯文字阅读大概需要3分钟。
内容图文
![使用Python和Beautiful Soup解析HTML](/upload/InfoBanner/zyjiaocheng/654/bfe01836d29e4dbc938ffcb4000cb9bc.jpg)
<div class="profile-row clearfix"><div class="profile-row-header">Member Since</div><div class="profile-information">January 2010</div></div>
<div class="profile-row clearfix"><div class="profile-row-header">AIGA Chapter</div><div class="profile-information">Alaska</div></div>
<div class="profile-row clearfix"><div class="profile-row-header">Title</div><div class="profile-information">Owner</div></div>
<div class="profile-row clearfix"><div class="profile-row-header">Company</div><div class="profile-information">Mad Dog Graphx</div></div>
我正在使用Beautiful Soup在HTML代码中达到这一点.我现在想搜索代码,并提取2010年1月,阿拉斯加,所有者和Mad Dog Graph之类的数据.所有这些数据都具有相同的类,但是它们之前具有不同的变量,例如“ Member since”,“ AIGA Chapter”等.我如何搜索“自此以来的会员”,然后获得2010年1月的信息?其他3个字段也是如此?
解决方法:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup('''<div class="profile-row clearfix"><div class="profile-row-header">Member Since</div><div class="profile-information">January 2010</div></div>
... <div class="profile-row clearfix"><div class="profile-row-header">AIGA Chapter</div><div class="profile-information">Alaska</div></div>
... <div class="profile-row clearfix"><div class="profile-row-header">Title</div><div class="profile-information">Owner</div></div>
... <div class="profile-row clearfix"><div class="profile-row-header">Company</div><div class="profile-information">Mad Dog Graphx</div></div>
... ''')
>>> for row in soup.findAll('div', {'class':'profile-row clearfix'}):
... field, value = row.findAll(text = True)
... print field, value
...
Member Since January 2010
AIGA Chapter Alaska
Title Owner
Company Mad Dog Graphx
当然,您可以使用字段和值执行任何操作,例如使用它们创建字典或将它们存储在数据库中.
如果“ profile-row clearfix” div中还有其他div或其他文本节点,则需要执行以下操作:field = row.find(‘div’,{‘class’:’profile-row-header’} ).findAll(text = True)等.
内容总结
以上是互联网集市为您收集整理的使用Python和Beautiful Soup解析HTML全部内容,希望文章能够帮你解决使用Python和Beautiful Soup解析HTML所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。