python – 使用beautifulsoup解析HTML页面
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 使用beautifulsoup解析HTML页面,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1796字,纯文字阅读大概需要3分钟。
内容图文
![python – 使用beautifulsoup解析HTML页面](/upload/InfoBanner/zyjiaocheng/803/2baa027233534a95a1d5fc6547c7866f.jpg)
我开始研究beautifulsoup来解析HTML.
例如对于网站“http://en.wikipedia.org/wiki/PLCB1”
import sys
sys.setrecursionlimit(10000)
import urllib2, sys
from BeautifulSoup import BeautifulSoup
site= "http://en.wikipedia.org/wiki/PLCB1"
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
table = soup.find('table', {'class':'infobox'})
#print table
rows = table.findAll("th")
for x in rows:
print "x - ", x.string
在某些有url的情况下,我输出为None.为什么会这样?
输出:
x - Phospholipase C, beta 1 (phosphoinositide-specific)
x - Identifiers
x - None
x - External IDs
x - None
x - None
x - Molecular function
x - Cellular component
x - Biological process
x - RNA expression pattern
x - Orthologs
x - Species
x - None
x - None
x - None
x - RefSeq (mRNA)
x - RefSeq (protein)
x - Location (UCSC)
x - None
例如,在Location之后,还有一个包含“pubmed search”但显示为None.我想知道它为什么会发生.
和
第二:有没有办法在字典中获得th和各自的td,以便它易于解析?
解决方法:
如果元素中直接有文本,则Element.string仅包含值.嵌套元素不包括在内.
如果您使用的是BeautifulSoup 4,请使用Element.stripped_strings代替:
print ''.join(x.stripped_strings)
对于BeautifulSoup 3,您需要搜索所有文本元素:
print ''.join([unicode(t).strip() for t in x.findAll(text=True)])
如果你想组合< th>和< td>将元素放入字典中,你就可以遍历所有< th>元素,然后使用.findNextSibling()来定位相应的< td>元素,并将其与上面的.findAll(text = True)技巧结合起来构建自己的字典:
info = {}
rows = table.findAll("th")
for headercell in rows:
valuecell = headercell.findNextSibling('td')
if valuecell is None:
continue
header = ''.join([unicode(t).strip() for t in headercell.findAll(text=True)])
value = ''.join([unicode(t).strip() for t in valuecell.findAll(text=True)])
info[header] = value
内容总结
以上是互联网集市为您收集整理的python – 使用beautifulsoup解析HTML页面全部内容,希望文章能够帮你解决python – 使用beautifulsoup解析HTML页面所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。