簡體   English   中英

使用BeautifulSoup遍歷整個表嗎?

[英]Iterate through an entire table with BeautifulSoup?

嘗試在此網站上列出的玩家上抓取所有玩家名稱和幻想信息。 我可以找到該表,但是當我嘗試遍歷整個表時麻煩就開始了。 這是我到目前為止編寫的代碼:

from bs4 import BeautifulSoup
from urllib.request import urlopen

nfl = 'http://www.fantasypros.com/nfl/adp/overall.php'
html = urlopen(nfl)
soup = BeautifulSoup(html.read(), "lxml")

table = soup.find('tbody').find_next('tbody')

playername = table.find('td').find_next('td')
for row in table:
    print(playername)

預期產量:

Adrian Peterson MIN, 5
Le'Veon Bell PIT, 11

等等,以此類推。

實際輸出

Adrian Peterson MIN, 5 
Adrian Peterson MIN, 5 
Adrian Peterson MIN, 5 

如此反復超過400次。

我的for循環哪里出問題了?

您需要在特定表的上下文中進行搜索:

for row in table:
    print(row.find('td').find_next('td'))

不過,我會以不同的方式處理這個問題。 所需表的id

table = soup.find('table', id="data")
for row in table.find_all("tr")[1:]:  # skipping header row
    cells = row.find_all("td")
    print(cells[0].text, cells[1].find('a').text)

打印:

(u'1', u'Adrian Peterson')
(u'2', u"Le'Veon Bell")
(u'3', u'Eddie Lacy')
(u'4', u'Jamaal Charles')
(u'5', u'Marshawn Lynch')
...

暫無
暫無

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

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