网络篮球参考如何排除4月的季后赛

2024-03-28 11:23:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我在刮this page。在

我本来可以从10月到3月的结果出来,但是4月份我遇到了问题,因为季后赛有一个thead,而且它显示了ValueError: Unknown string format。我想刮擦结束或跳过这一行。在

我的代码是:

data = [[td.getText() for td in data_rows[i].findAll(['th','td'])] for i in range(len(data_rows))]

Tags: 代码informatfordatastringpagethis
1条回答
网友
1楼 · 发布于 2024-03-28 11:23:59

循环使用tr元素,确保您没有进入“季后赛”tr,然后继续:

from bs4 import BeautifulSoup
from urllib.request import urlopen

webpage = urlopen("https://www.basketball-reference.com/leagues/NBA_2017_games-april.html")
soup = BeautifulSoup(webpage, 'html.parser')
data_rows = soup.find('table', {"id": "schedule"}).find_all('tr') # find all the 'tr' elements

for tr in data_rows: 
    if tr.text.strip() != "Playoffs": # check if were on the 'Playoffs' title tr
        data = [td.text for td in tr.find_all(["td", "th"])]
        print(data)

如果您使用的是beauthoulsoup的最新版本,请注意^{} is deprecated。请改用find_all()。类似地,使用.text而不是getText()

相关问题 更多 >