使用beautifulsoup解析HTML页面

sam*_*sam 4 html python beautifulsoup

我开始研究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
Run Code Online (Sandbox Code Playgroud)

在某些有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
Run Code Online (Sandbox Code Playgroud)

例如,在Location之后,还有一个包含"pubmed search"但显示为None.我想知道它为什么会发生.


第二:有没有办法让次和相应的TD在字典中,这样就很容易解析?

Mar*_*ers 5

Element.string如果元素中直接有文本,则只包含一个值.嵌套元素不包括在内.

如果您使用的是BeautifulSoup 4,请Element.stripped_strings改用:

print ''.join(x.stripped_strings)
Run Code Online (Sandbox Code Playgroud)

对于BeautifulSoup 3,您需要搜索所有文本元素:

print ''.join([unicode(t).strip() for t in x.findAll(text=True)])
Run Code Online (Sandbox Code Playgroud)

如果你想将元素<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
Run Code Online (Sandbox Code Playgroud)