为什么美丽的汤不能显示表中的所有数据?

时间:2011-05-18 03:40:47

标签: python web-scraping beautifulsoup

一周前我试图翻页维基百科。但我无法弄清楚为什么Beautiful Soup只会在表格列中显示一些字符串,并为其他表格列显示“无”。

注意:表列都包含数据。

我的程序将使用标签“description”提取所有表格列。我试图从表中提取所有描述。

我正在抓的网站是:http://en.wikipedia.org/wiki/Supernatural_(season_6

这是我的代码:

from BeautifulSoup import BeautifulSoup 
import urllib
import sys
from urllib import FancyURLopener

class MyOpener(FancyURLopener):
    version = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.65 Safari/534.24'


def printList(rowList):
    for row in rowList:
        print row
        print '\n'

    return

url = "http://en.wikipedia.org/wiki/Supernatural_(season_6)"

#f = urllib.urlopen(url)
#content = f.read()
#f.close

myopener = MyOpener()
page = myopener.open(url)
content = page.read()
page.close()

soup = BeautifulSoup(''.join(content))
soup.prettify()

movieList = []

rowListTitle = soup.findAll('tr', 'vevent')
print len(rowListTitle)

#printList(rowListTitle)
for row in rowListTitle:
    col = row.next # explain this?
    if col != 'None':
        col = col.findNext("b")
        movieTitle = col.string
        movieTuple = (movieTitle,'')
        movieList.append(movieTuple)

#printList(movieList)

for row in movieList:
    print row[0]

rowListDescription = soup.findAll('td' , 'description')
print len(rowListDescription)


index = 1;
while ( index < len(rowListDescription) ):
    description = rowListDescription[index]
    print description
    print description.string
    str = description
    print '####################################'
    movieList[index - 1] = (movieList[index - 1][0],description)
    index = index + 1

我没有粘贴输出,因为它很长。但输出真的很奇怪,因为它设法捕获<td>中的信息,但是当我做.string时,它给了我一个空的内容。

1 个答案:

答案 0 :(得分:0)

所有描述字符串都是空的吗?来自文档:

  

为方便起见,如果标记只有一个子节点,并且该子节点是字符串,则子节点可用作tag.string,以及tag.contents [0]。

在这种情况下,描述通常有子节点,即:<a>链接到另一篇维基百科文章。这将计为非字符串子节点,在这种情况下,描述节点的string设置为None