http://projects.fivethirtyeight.com/election-2016/delegate-targets/の下部にあるテーブルからデータを取得しようとしています。Python:XPathを使用してテーブルからデータを取得する
import requests
from lxml import html
url = "http://projects.fivethirtyeight.com/election-2016/delegate-targets/"
response = requests.get(url)
doc = html.fromstring(response.text)
tables = doc.findall('.//table[@class="delegates desktop"]')
election = tables[0]
election_rows = election.findall('.//tr')
def extractCells(row, isHeader=False):
if isHeader:
cells = row.findall('.//th')
else:
cells = row.findall('.//td')
return [val.text_content() for val in cells]
import pandas
def parse_options_data(table):
rows = table.findall(".//tr")
header = extractCells(rows[1], isHeader=True)
data = [extractCells(row, isHeader=False) for row in rows[2:]]
return pandas.DataFrame(data, columns=header)
election_data = parse_options_data(election)
election_data
私は候補者の名前( 『トランプ』、 『クルス』、 『Kasich』)との一番上の行とのトラブルを抱えています。 trクラス= "トップ"の下にあり、今はtrクラス= "ボトム"(「ウォン/ターゲット」という行から始まる)だけです。
ご協力いただきありがとうございます。