python - 将 python 字典转换为 pandas 数据框,但这段代码不允许我这样做。(NBA 数据转义)
问题描述
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display
def get_basketball_stats(link='https://en.wikipedia.org/wiki/Michael_Jordan'):
michael_jordan_dict=get_basketball_stats('https://en.wikipedia.org/wiki/Michael_Jordan')
kobe_bryant_dict=get_basketball_stats('https://en.wikipedia.org/wiki/Kobe_Bryant')
lebron_james_dict=get_basketball_stats('https://en.wikipedia.org/wiki/LeBron_James')
stephen_curry_dict=get_basketball_stats('https://en.wikipedia.org/wiki/Stephen_Curry')
response = requests.get(link)
soup = bs4.BeautifulSoup(response.text, 'html.parser')
df = pd.DataFrame(michael_jordan_dict)
#is this right?^^
df.head()
我相信我没有正确创建字典。我怎样才能解决这个问题?
解决方案
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display
import requests
from bs4 import BeautifulSoup
#Define a Function
def get_basketball_stats(link='https://en.wikipedia.org/wiki/Michael_Jordan'):
response = requests.get(link)
soup = BeautifulSoup(response.text, 'html.parser') #we got the whole webpage code as HTML
#You need to specify which element of HTML you need, our case we need table element
#The table is in the class "wikitable sortable"
#Right click in the webpage and click inspect (TO view HTML code) then u can inspect specific element
table = soup.find("table", { "class" : "wikitable sortable" })
df = pd.read_html(str(table))
return(df[0])
#Use the Function by calling it: get_basketball_stats('url')
#Here we called the function and stored in the variable
michael_jordan_dict=get_basketball_stats('https://en.wikipedia.org/wiki/Michael_Jordan')
kobe_bryant_dict=get_basketball_stats('https://en.wikipedia.org/wiki/Kobe_Bryant')
lebron_james_dict=get_basketball_stats('https://en.wikipedia.org/wiki/LeBron_James')
stephen_curry_dict=get_basketball_stats('https://en.wikipedia.org/wiki/Stephen_Curry')
stephen_curry_dict.head() #we called the variable
HTML(标签、类)、Python 定义函数、Pandas
推荐阅读
- python - 定义和使用自定义渲染器 Django Rest Framework 视图
- spring-boot - 使用 Spring 和 OAuth2 向用户注册添加激活码
- matlab - 梯度下降和正规方程没有给出相同的结果,为什么?
- spring-security - Spring Security 和多个分层角色
- html - iFrame 内的 Div 100% 高度
- python - 解压数据框字典并将键设置为列值
- oop - 合同设计
- java - install4j:在 MacOS 上安装的应用程序不运行
- bash - 正则表达式 101 与 SED
- javascript - 将表单文本字段输入读取为 php 变量