2016-03-28 241 views
0

我試圖從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」開始)。

任何幫助非常感謝!

回答

0

候選人的名字是第0行中:

candidates = [val.text_content() for val in rows[0].findall('.//th')[1:]] 

或者,如果重複使用相同的extractCells()功能:在這裏

candidates = extractCells(rows[0], isHeader=True)[1:] 

[1:]片是跳過第一個空th細胞。

0

不好(硬編碼),但運行,因爲你想。

def parse_options_data(table): 
    rows = table.findall(".//tr") 
    candidate = extractCells(rows[0], isHeader=True)[1:]                                    
    header = extractCells(rows[1], isHeader=True)[:3] + candidate 
    data = [extractCells(row, isHeader=False) for row in rows[2:]] 
    return pandas.DataFrame(data, columns=header)