美丽的汤错误:列表索引超出范围



我是一个**非常新的python程序员。使用urllib和beautifulsoup开发一个网络爬虫。请忽略顶部的while循环和i的递增,我只是运行这个测试版本,并且为一个页面,但它最终将包括一整套。我的问题是,这得到汤,但产生一个错误。我不确定我是否正确地收集了表数据,但我希望这段代码可以忽略链接,只将文本写入.csv文件。现在我专注于将文本正确地打印到屏幕上。

line 17, in <module>
    uspc = col[0].string
IndexError: list index out of range

代码如下:

import urllib
from bs4 import BeautifulSoup
i=125
while i==125:
    url = "http://www.uspto.gov/web/patents/classification/cpc/html/us" + str(i) + "tocpc.html"
    print url + 'n'
    i += 1
    data = urllib.urlopen(url).read()
    print data
    #get the table data from dump
    #append to csv file
    soup = BeautifulSoup(data)
    table = soup.find("table", width='80%')
    for row in table.findAll('tr')[1:]:
        col = row.findAll('td')
        uspc = col[0].string
        cpc1 = col[1].string
        cpc2 = col[2].string
        cpc3 = col[3].string
        record = (uspc, cpc1, cpc2, cpc3)
        print "|".join(record)

最后,我通过修改下面一行来解决这个问题:

for row in table.findAll('tr')[1:]:

:

for row in table.findAll('tr')[2:]:

错误是由于表的第一行有分割列

最新更新