【问题标题】:Why Beautiful Soup cannot display all <td> data in the tables?为什么 Beautiful Soup 无法显示表格中的所有 <td> 数据?
【发布时间】:2011-05-18 03:40:46
【问题描述】:

我在一周前尝试翻页抓取维基百科。但我不明白为什么 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

我没有粘贴输出,因为它真的很长。但是输出真的很奇怪,因为它确实设法捕获了&lt;td&gt; 中的信息,但是当我执行.string 时,它给了我一个空的内容。

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢卡米尔。 tag.contents[0] 确实有助于检索第一个 NavigableString。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多