【问题标题】:Scrape specific NHL score with Python Beautifulsoup使用 Python Beautifulsoup 获取特定的 NHL 分数
【发布时间】:2015-02-02 21:34:35
【问题描述】:

我正在尝试仅获取指定团队的总分。我写了以下内容:

import urllib.request
import re
from bs4 import BeautifulSoup

#url1 = "http://scores.nbcsports.com/nhl/scoreboard.asp"

## This works, however is using a set day for testing, will need url changed to url1 for current day scoreboard
url = "http://scores.nbcsports.com/nhl/scoreboard.asp?day=20141202"
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page)

allrows = soup.findAll('td')
userows = [t for t in allrows if t.findAll(text=re.compile('Vancouver'))]

print(userows)

这会返回:

[<td><table cellspacing="0"><tr class="shsTableTtlRow"><td class="shsNamD" colspan="1">Final</td>
<td class="shsTotD">1</td>
<td class="shsTotD">2</td>
<td class="shsTotD">3</td>
<td class="shsTotD">Tot</td>
</tr>
<tr>
<td class="shsNamD" nowrap=""><span class="shsLogo"><span class="shsNHLteam22sm_trans"></span></span><a href="/nhl/teamstats.asp?teamno=22&amp;type=stats">Vancouver</a></td>
<td class="shsTotD">1</td>
<td class="shsTotD">2</td>
<td class="shsTotD">1</td>
<td class="shsTotD">4</td>
</tr>
<tr>
<td class="shsNamD" nowrap=""><span class="shsLogo"><span class="shsNHLteam23sm_trans"></span></span><a href="/nhl/teamstats.asp?teamno=23&amp;type=stats">Washington</a></td>
<td class="shsTotD">0</td>
<td class="shsTotD">2</td>
<td class="shsTotD">1</td>
<td class="shsTotD">3</td>
</tr>
</table>
</td>, <td class="shsNamD" nowrap=""><span class="shsLogo"><span class="shsNHLteam22sm_trans"></span></span><a href="/nhl/teamstats.asp?teamno=22&amp;type=stats">Vancouver</a></td>]

我似乎无法到达中间街区&lt;td class="shsTotD"&gt;4&lt;/td&gt; 中的4。如果只能获得 1 2 1 4 我可以比较这些值并总是选择最大的,但我什至似乎都无法做到这一点。提前致谢。

【问题讨论】:

    标签: python html web-scraping beautifulsoup html-parsing


    【解决方案1】:

    找到包含Vancouver的标签并使用find_next_siblings()获取下一个td标签:

    vancouver = soup.find('a', text='Vancouver')
    for td in vancouver.parent.find_next_siblings('td', class_='shsTotD'):
        print(td.text)
    

    打印:

    1
    2
    1
    4
    

    【讨论】:

    • 谢谢,正是我需要的。
    猜你喜欢
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2014-11-20
    • 2013-02-25
    • 2023-03-25
    相关资源
    最近更新 更多