2017-07-13 7 views
0

私は知事の選挙データをウェブから削り取ろうとしていますが、私はその一部を苦労しています。あなたは2つのケースで見ることができるように、2人の候補者(民主党または共和党)または3人の候補者(dem、repub、independent)がいます。美しいスープを使って、さまざまな状況で異なったフォーマットのデータをスクラップします

次のコードを書いてデータをスクラップしました。これは2つの候補の状況で動作しますが、どちらの状況でも動作させる方法がわかりません。

は、ここに私のコードです:

html = requests.get(url).text 

soup = BeautifulSoup(html, 'html.parser') 

#Scrape the percentage Numbers 
table = soup.find_all('table')[0] 
table_row = table.find_all('tr')[1] 
table_data = table_row.find_all('td')[3:5] 

CASE 1:

enter image description here

CASE 2:

enter image description here

+0

あなたが望む結果について質問を明確にしてください。 –

+0

クラススプレッドのtdには何が含まれていますか?あなたはその状態でそれを無視したい。 –

+0

現在、私のコードは[1:5]からtdを見つけたので、ケース1で動作しますが、2番目のケースでは[3:6]が必要です。私はこれらの状況の両方で掻き集めることができるコードを書く方法を確信していません – bugsyb

答えて

1
html = requests.get(url).text 
soup = BeautifulSoup(html, 'html.parser') 
table = soup.find_all('table')[0] 
table_row = table.find_all('tr')[1] 
table_data = table_row.find_all('td') 
if table_data[-1].class == 'spread': #checking whether the last td has class spread 
    table_data = table_data[3:5] 
else: 
    table_data = table_data[3:6] 
+0

大変感謝!あなたが欲しいものがまさにそれです – bugsyb

+0

あなたは大歓迎です –

関連する問題