2016-08-23 8 views
2

私は現在、Python 3.5とbs4でWebスクレイピングプログラムを構築中です。下のコードでは、url内の2つのテーブルからデータを取得しようとしました。私は最初のテーブルでは成功しますが、2番目のテーブルではエラーが発生します。エラーは "D.append(cells [0] .find(text = True))"の "IndexError:範囲外のリストインデックス"です。私は私に0,1,2を与える、「セルのためのリストのインデックスをチェックしているので、問題はないはず。誰もがこの問題を解決する上の任意のアイデアを提案してもらえますか?Webスクレイピングでリストのインデックスが範囲外になるエラー

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() 

答えて

1

あなたが期待しているように見えますこのコードは「目」と「TD」のどちらかを選択するが、それはしません。それは常に「目」を選択すると、その行には「目」は存在しないとき、空のリストを返します。

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') 
+1

ありがとうございました。それは動きます! –

+0

それはあなたのために働いてうれしい。これがあなたの選択された答えであれば、私の答えを受け入れてください。 –

+0

私は投票ボタンをクリックすることでそれを受け入れました。それは動作しますか? –

関連する問題