【发布时间】:2021-05-19 19:35:58
【问题描述】:
Python 新手,所以这可能是一个基本问题,但我有下表:
https://www.sports-reference.com/cfb/years/1991-passing.html
我想用BeautifulSoup 刮掉它,得到这样的输出:
| Player | School | Conf | all the way to TD under Rushing |
|---|---|---|---|
| Ty Detmer | Brigham Young | WAC | 7 |
| Player Two | School Two | Conf 2 | 5 |
问题 1:如果您查看上面的 URL,每 21 行都是应该忽略的标题行
问题2:“Rushing”似乎是另一个th所以我下面的代码和输出目前是这样的:
import requests
import lxml.html as lh
import pandas as pd
from bs4 import BeautifulSoup
data_universe = {}
years = list(range(1990,1991))
COLUMNS = ['Player', 'School', 'Conf', 'G', 'Cmp', 'Att', 'Pct', 'Yds', 'Y/A', 'AY/A', 'TD', 'Int', 'Rate', 'Rush_Att', 'Rush_Yds', 'Avg', 'Rush_TD']
for year in years:
url = 'https://www.sports-reference.com/cfb/years/%s-passing.html' %year
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
parsed_table = soup.find_all('table')[0]
rows = parsed_table.find_all("tr")
cy_data = []
for row in rows[2:]:
cells = row.find_all("td")
cells = cells[0:18]
cy_data.append([cell.text for cell in cells]) # For each "td" tag, get the text inside it
cy_data = pd.DataFrame(cy_data, columns=COLUMNS)
pd.set_option("display.max_rows", None, "display.max_columns", None)
print(cy_data.head())
输出:
如何像在网站上一样在数据框中整齐地格式化此表?
【问题讨论】:
标签: python pandas dataframe beautifulsoup html-parsing