我开始使用 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 的内容。我想知道为什么会这样。
and
第二:有没有办法在字典中获取 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>
and <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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)