[英]How to scrape data from last table on website
我正在嘗試使用以下代碼從該網站上抓取“每場比賽的球隊統計數據”表:
from urllib.request import urlopen as uo
from bs4 import BeautifulSoup as BS
import pandas as pd
url = 'https://www.basketball-reference.com/leagues/NBA_2020.html'
html = uo(url)
soup = BS(html, 'html.parser')
soup.findAll('tr')
headers = [th.getText() for th in soup.findAll('tr')]
headers = headers[1:]
print(headers)
rows = soup.findAll('tr')[1:]
team_stats = [[td.getText() for td in rows[i].findAll('td')]
for i in range(len(rows))]
stats = pd.DataFrame(team_stats, columns=headers)
但它返回此錯誤:
AssertionError: 71 columns passed, passed data had 212 columns
問題是數據隱藏在 HTML 的注釋部分中。 您要提取的表格在您的瀏覽器中使用 Javascript 呈現。 使用 requests 或 urllib 請求頁面只會產生原始 HTML。
因此請注意,如果您使用 BeautifulSoup 搜索要查找的正確標簽,則必須使用“查看頁面源”而不是使用“檢查元素”檢查呈現的頁面的源代碼。
試試這個:
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = 'https://www.basketball-reference.com/leagues/NBA_2020.html'
html = requests.get(url)
section_start = '<span class="section_anchor" id="team-stats-per_game_link" data-label="Team Per Game Stats">'
block_start = html.text.split(section_start)[1].split("<!--")[1]
block = block_start.split("-->")[0]
soup = BeautifulSoup(block)
data = [th.get_text(",") for th in soup.findAll('tr')]
header = data[0]
header = [x.strip() for x in header.split(",") if x.strip() !=""]
data = [x.split(",") for x in data[1:]]
pd.DataFrame(data, columns=header)
說明:您首先需要通過簡單地拆分該部分之前的原始 HTML 來找到注釋部分。 您將該部分提取為文本,轉換為 soup,然后進行解析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.