【发布时间】:2021-04-18 23:55:05
【问题描述】:
我对使用 python/BeautifulSoup/urllib.request 进行网络抓取非常陌生,并且一直在尝试弄清楚如何抓取该表的时间最长。我在网上找到了一些其他代码并进行了尝试,并一直在尝试了解它们的工作原理并对其进行修改,但是它们总是会过滤掉我需要的第一列。
代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
import numpy
# NBA season we will be analyzing
month = "january"
# URL page we will scrape (see image above)
url = "https://www.basketball-reference.com/leagues/NBA_2021_games-{}.html".format(month)
# this is the HTML for given URL
html = urlopen(url)
soup = BeautifulSoup(html)
# use findALL() to get the column headers
soup.findAll()
# use getText()to extract the text we need into a list
headers = [th.getText() for th in soup.findAll('tr', limit=2)[0].findAll('th')]
# exclude the first column as we will not need the ranking order from Basketball Reference for the analysis
headers=headers[1:]
# avoid the first header row
rows = soup.findAll('tr')[1:]
player_stats = [[td.getText() for td in rows[i].findAll('td')]
for i in range(len(rows))]
df = pd.DataFrame(player_stats, columns = headers)
This is what the HTML table looks like
谁能告诉我如何从这个网站上抓取表格?我这辈子都想不通 https://www.basketball-reference.com/leagues/NBA_2021_games-january.html
【问题讨论】:
-
如果你不能让它工作也没关系,但请分享你期望工作的代码,并解释你为什么认为它不工作,或者你遇到问题的部分。你说你已经有了一些 Python 代码,所以这是一个很好的起点。
-
我想我明白了。应该贴在上面。所以我遇到的问题是它不包括第一列。我知道第一列是与其他列不同类型的标签,但我不知道如何在我的数据框中获取它
-
好的,我们可以看到代码了。 (请在以后修复缩进和格式,我这次做了)。
-
嘿,非常感谢!我将研究代码以找出我哪里出错以及你做了什么。非常感谢!
-
啊,现在才看到您的实际问题,第一列有
<th>而不是<td>元素 - 会调整。
标签: python web-scraping beautifulsoup