我现在正在使用 Python 3.5 和 bs4 构建一个网络抓取程序。在下面的代码中,我试图从 url 中的两个表中检索数据。我在第一个表中成功,但第二个表中出现错误。对于“D.append(cells[0].find(text=True))”,错误是“IndexError:列表索引超出范围”。我已经检查了“单元格”的列表索引,它给了我 0、1、2,所以应该没问题。有人可以提出解决这个问题的任何想法吗?
import tkinter as tk
def test():
from bs4 import BeautifulSoup
import urllib.request
import pandas as pd
url_text = 'http://www.sce.hkbu.edu.hk/future-students/part-time/short-courses-regular.php?code=EGE1201'
resp = urllib.request.urlopen(url_text)
soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'))
all_tables=soup.find_all('table')
print (all_tables)
right_table=soup.find('table', {'class' : 'info'})
A=[]
B=[]
C=[]
for row in right_table.findAll("tr"):
cells = row.findAll('td')
A.append(cells[0].find(text=True))
B.append(cells[1].find(text=True))
C.append(cells[2].find(text=True))
df=pd.DataFrame()
df[""]=A
df["EGE1201"]=C
print(df)
D=[]
E=[]
F=[]
right_table=soup.find('table', {'class' : 'schedule'})
for row in right_table.findAll("tr"):
try:
cells = row.findAll('th')
except:
cells = row.findAll('td')
D.append(cells[0].find(text=True))
E.append(cells[1].find(text=True))
F.append(cells[2].find(text=True))
df1=pd.DataFrame()
df[D[0]]=D[1]
df[E[0]]=E[1]
df[F[0]]=F[1]
print(df1)
if __name__ == '__main__':
test()
请您参考如下方法:
看起来您希望此代码在“th”和“td”之间进行选择,但它不会。它将始终选择“th”,并在该行中没有“th”时返回一个空列表。
try:
cells = row.findAll('th')
except:
cells = row.findAll('td')
相反,我会更改代码以检查列表是否为空,然后请求“td”:
cells = row.findAll('th')
if not cells:
cells = row.findAll('td')
或者,您可以将代码缩短为:
cells = row.findAll('th') or row.findAll('td')
