首页 > 解决方案 > 尝试使用 python 解析来自 html 的数据,但在获取表格行元素后不知道如何进行

问题描述

我正在尝试从酋长网站获取数据并将它们放在 python 中以使用 matplotlib 进行操作。我可以将其缩小到表格行,但不知道之后如何进行。我希望它们与(att、comp、yds、comp% 等)连续排列,然后进行 stdev 和其他数学运算。

到目前为止,我的代码是关于尝试获取表格上的数据。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import requests
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "https://www.chiefs.com/team/stats/"
html = urlopen(url)
soup = BeautifulSoup(html, 'lxml')
type(soup)
rows = soup.find_all('tr')
rows
print(rows[:10])

我有所有的信息,但我不知道如何进行。 这是我想要的数字

标签: pythonhtmlparsingweb-scraping

解决方案


使用 pandasread_html函数获取表格。请注意,它返回一个数据框列表,因此您必须决定您想要哪些。这里看起来 t[0] 正在传递,t[1] 正在冲,t[2] 正在接收,等等。

>>> import pandas as pd
... url = 'https://www.chiefs.com/team/stats/'
... t = pd.read_html(url)

>>> len(t)
9

>>> t[0]

            Player  ATT  COMP   YDS   COMP%  YDS/ATT  TD   TD%  INT    INT%  LONG  SCK  SCK/LOST   RATE
0    Sammy Watkins    1     0     0    0.00      0.0   0  0.00    1  100.00   NaN    0         0    0.0
1   Tommy Townsend    1     1    13  100.00     13.0   0  0.00    0    0.00  13.0    0         0  118.8
2  Patrick Mahomes  588   390  4740   66.33      8.1  38  6.46    6    1.02  75.0   22       147  108.2
3     Travis Kelce    2     1     4   50.00      2.0   0  0.00    0    0.00   4.0    0         0   56.3
4       Chad Henne   38    28   248   73.68      6.5   2  5.26    0    0.00  37.0    2         4  108.2

推荐阅读