2017-05-21 12 views
0

特定のデータについてウェブサイトを廃止しています。 私のコードは一点までうまく動作します。特定のテーブルと行を探して、そのセルを選択し、それらをdictに配置します。私の問題は、行の最後のセルを選択することです。テーブル内の特定のtdを掻き集める

import urllib 
import urllib.request 
from bs4 import BeautifulSoup 
import re 
import os 
import pandas as pd 

theurl = "http://www.nationsonline.org/oneworld/IATA_Codes/airport_code_list.htm" 
thepage = urllib 
thepage = urllib.request.urlopen(theurl) 
soup=BeautifulSoup(thepage, "html.parser") 
air=[] 
init_data = open('/Users/paribaker/Desktop/air.txt', 'a') 
count = 0 
while count <73: 
    title = soup.find_all('table',{'class':'tb86'})[(count)] 
    rows = title.findAll('tr')[1:] 
    data = { 
     'city' : [], 
     'country' : [], 
     'code' :[] 

     } 
    for row in rows: 
     col1 = row.find_all('td')[0] 
     col2 = row.find_all('td')[1] 
     col3 = row.find_all('td')[2] 
     print (col1.text) 
     print(col2.text) 
     print(col3.text) 
     #col3 = row.find_all('td')[1] 
     #data['city'].append(col1.get_text()) 
     #data['country'].append(col2) 
     #data['code'].append(col3) 
     #dogData = pd.DataFrame(data) 
     #dogData.to_csv("dog.csv") 
    count += 3 

td [2]が範囲内にないというエラーが表示されます。私がtdのセレクタを見ると、それは3番目のものなので、私は[2]を使います。

答えて

0

一部のデバッグ文では、一部の行に2つしかないことがわかります。実際には、これは非常に最初のrowrows中のために真である:

for i, row in enumerate(rows): 
    print("Row {}:\n".format(i)) 
    for j, td in enumerate(row.find_all('td')): 
     print(" Cell {}:\n{}".format(j, td)) 
    try: 
     col3 = row.find_all('td')[2] 
    except IndexError as e: 
     print("ERROR on Row {}: {}".format(i, e)) 
     break 

出力:

Row 0: 

Cell 0: 
<td style="width:730px;"><script async="" src="http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><!-- Top-Banner 728x90, Erstellt 25.12.09 --><ins class="adsbygoogle" data-ad-client="ca-pub-7193398479241689" data-ad-slot="6570665833" style="display:inline-block;width:728px;height:90px"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></td> 

Cell 1: 
<td class="logotd"><a href="/oneworld/first.shtml"><img alt="Nations Online Logo" class="displayed" height="60" src="/buttons/OWNO_logo06-60.png" width="60"/> </a><br><b>One World<br>Nations Online</br></b></br></td> 

ERROR on Row 0: list index out of range 

おそらく、あなたはスキップすることをスクレイピングしているページでは、いくつかの <td>要素がありますか?

UPDATE
は、ここであなたが取得している掻き取り、出力を絞り込むための一つの方法です。あなたが興味を持っている細胞が、クラスborder1のメンバーであるようです。あなたはこのクラスで細胞を含む行をフィルタリングすることができます

for row in rows: 
    target_row = row.find_all('td', class_="border1") 
    if len(target_row) == 3: 
     city, country, code = [td.text for td in target_row] 
     print("City: {}, Country: {}, Code: {}".format(city, country, code)) 

出力:

City: Aarhus, Country: Denmark, Code: AAR 
City: Abadan, Country: Iran, Code: ABD 
City: Abeche, Country: Chad, Code: AEH 
... 
City: Zinder, Country: Niger, Code: ZND 
City: Zouerate, Country: Mauritania, Code: OUZ 
City: Zurich (Zürich) - Kloten, Country: Switzerland, Code: ZRH 
+0

だけでなく、私はすべてのテーブルもすべての行をこするわけではありません。私はすべての3番目のテーブルを掻き取り、最初のテーブルを除くすべての行を掻き取るだけです。各行には、都市、国、コードの3つのデータポイントがあります。私は3つすべてを集めようとしています。すべての行がすべて3の値を持っているテーブルを見て、私は何かを逃していますか? –

+0

私の投稿した出力はあなたのコードからまっすぐですが、デバッグステートメントが追加されています。これらのセルの内容は、都市/国/コードのデータではありません。 –

+0

私の更新された答えを見てください - あなたが興味を持っているデータに絞る方法を示しました。一般に、要素タグ名(td、tr、あなたが望むものを正確に得ることができます。 –

関連する問題