簡體   English   中英

使用Python和BeautifulSoup解析表

[英]Using Python and BeautifulSoup to Parse a Table

我正在嘗試使用Python和BeautifulSoup訪問某些td標簽中的內容。 我可以獲取第一個符合條件的td標簽(使用find),也可以全部獲取(使用findAll)。

現在,我可以使用findAll,全部獲取它們,然后從中獲取想要的內容,但這似乎效率很低(即使我對搜索設置了限制)。 無論如何,是否有符合我想要標准的特定td標簽? 說第三還是第十?

到目前為止,這是我的代碼:

from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from mechanize import Browser
from BeautifulSoup import BeautifulSoup

br = Browser()
url = "http://finance.yahoo.com/q/ks?s=goog+Key+Statistics"
page = br.open(url)
html = page.read()
soup = BeautifulSoup(html)
td = soup.findAll("td", {'class': 'yfnc_tablehead1'})

for x in range(len(td)):
    var1 = td[x]
    var2 = var1.contents[0]
    print(var2)

無論如何,是否有符合我想要標准的特定td標簽? 說第三還是第十?

好...

all_tds = [td for td in soup.findAll("td", {'class': 'yfnc_tablehead1'})]

print all_tds[3]

...沒有其他辦法了。

findfindAll非常靈活, BeautifulSoup.findAll文檔說

5.您可以傳入一個將Tag對象作為其唯一參數的可調用對象,並返回一個布爾值。 findAll遇到的每個Tag對象都將傳遞到此對象,如果調用返回True,則認為該標簽匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM