使用beautifulsoup解析HTML页面


问题内容

我开始研究用于解析HTML的beautifulsoup。
例如网站“ 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

在有网址的某些情况下,我得到的输出为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

例如,在位置之后,还有一个包含“已发布搜索”但显​​示为“无”的词。我想知道为什么会这样。


第二:有没有办法让词典日和相应的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