2016-06-07 115 views
1

我已經添加了希望刮取的html代碼片段。Python xml - 如何循環訪問<tbody>以獲得數據

我想穿過每一行(tbody)並使用xml刮取相關數據。

每一行的XSS可以通過以下發現:

//*[@id="re_"]/table/tbody 

但林不知道該如何在python通過每個TBODY將它設置爲循環?沒有tbody行的設置編號,因此可以包含任何數字。 例如。下面

for each tbody: 
     ...get data 

是HTML頁面

http://www.racingpost.com/horses/result_home.sd?race_id=651402&r_date=2016-06-07&popup=yes#results_top_tabs=re_&results_bottom_tabs=ANALYSIS

+0

你可以添加你正在刮的賽車鏈接嗎? –

+0

對不起,我已添加實際頁面本身 –

+0

您目前正在使用哪些庫? –

回答

1

使用LXML,你可以拉桌子直接使用類名,並提取所有的TBODY標籤與XPath的//table[@class="grid resultRaceGrid"]/tbody

from lxml import html 

x = html.parse("http://www.racingpost.com/horses/result_home.sd?race_id=651402&r_date=2016-06-07&popup=yes#results_top_tabs=re_&results_bottom_tabs=ANALYSIS") 

tbodys= x.xpath('//table[@class="grid resultRaceGrid"]/tbody') 
# iterate over the list of tbody tags 
for tbody in tbodys: 
    # get all the rows from the tbody 
    for row in tbody.xpath("./tr"): 
     # extract the tds and do whatever you want. 
     tds = row.xpath("./td") 
     print(tds) 

很明顯,你可以更具體,在TD標籤具有類名稱的這你可以使用提取和一些tr標籤也有類。

+0

爲什麼運行時它會得到[上的負載] –

+0

你期望得到什麼?代碼從每一行拉動所有td標籤 –

+0

doh - 我一定很累 - 謝謝你 –

-1

我想你會感興趣BeautifulSoup

與您的數據,如果你想打印所有的註釋文本,這將是簡單的:

from bs4 import BeautifulSoup 
soup = BeautifulSoup(html_doc, 'html.parser') 

for tbody in soup.find_all('tbody'): 
    print tbody.find('.commentText').get_text() 

你可以做更多花哨的東西。您可以read more here

+0

如果downvote的原因是tbody,那麼這不是問題的一部分。如何生成html是無關緊要的。該怎麼做 - 是。 – zEro