我試圖從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
我遇到了與候選人的名字('特朗普','克魯斯','卡西奇')最高行的麻煩。它在tr class =「top」之下,現在我只有tr class =「bottom」(從「won/target」開始)。
任何幫助非常感謝!