【发布时间】:2020-07-31 06:45:44
【问题描述】:
我正在尝试从 Fangraphs 中抓取数据。这些表分为 21 页,但所有页面都使用相同的 url。我对网络抓取(或一般的 Python)非常陌生,但 Fangraphs 没有公共 API,所以抓取页面似乎是我唯一的选择。我目前正在使用 BeautifulSoup 来解析 HTML 代码,并且我能够抓取初始表,但它只包含前 30 个玩家,但我想要整个玩家池。两天的网络搜索,我被困住了。链接和我当前的代码如下。我知道他们有一个下载 csv 文件的链接,但这在整个赛季都会变得乏味,我想加快数据收集过程。任何方向都会有所帮助,谢谢。
https://www.fangraphs.com/projections.aspx?pos=all&stats=bat&type=fangraphsdc
import requests
import pandas as pd
url = 'https://www.fangraphs.com/projections.aspx?pos=all&stats=bat&type=fangraphsdc&team=0&lg=all&players=0'
response = requests.get(url, verify=False)
# Use BeautifulSoup to parse the HTML code
soup = BeautifulSoup(response.content, 'html.parser')
# changes stat_table from ResultSet to a Tag
stat_table = stat_table[0]
# Convert html table to list
rows = []
for tr in stat_table.find_all('tr')[1:]:
cells = []
tds = tr.find_all('td')
if len(tds) == 0:
ths = tr.find_all('th')
for th in ths:
cells.append(th.text.strip())
else:
for td in tds:
cells.append(td.text.strip())
rows.append(cells)
# convert table to df
table = pd.DataFrame(rows)
【问题讨论】:
标签: python url web-scraping beautifulsoup