通过selenium获取NBA官网球员前五页的信息
使用工具及其安装
- PyCharm
- Selenium:pip install selelnium -i https://pypi.douban.com/simple
- pandas:pip install pandas -i https://pypi.douban.com/simple
- BeautifulSoup: pip install beautifulsoup4
- 本例使用的是谷歌浏览器,根据自己的版本选择驱动。
基本步骤
- 导入相关的模块和包,并创建Webdriver实例,打开网页,其官网网址:https://www.nba.com/stats/players/traditional/?sort=AGE&dir=-1
官网页面:
- 使用Beautifulsoup解析html页面后获取表格区域标签,在调用pandas的read_html返回所有的表格数据列表,再将数据存为csv文件格式。
- 使用selelnium模拟点击下一页的按钮并调用click()。这里定义为爬取前五页的信息。
具体实现代码如下:
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
import time
#NBA官网
url='https://www.nba.com/stats/players/traditional/?sort=AGE&dir=-1'
driver=webdriver.Chrome("chromedriver.exe")
driver.implicitly_wait(10)
driver.get(url)#获取页面信息
#获取每一页的表格数据
page_num=1
pages_all=True
while pages_all:
soup=BeautifulSoup(driver.page_source,'lxml')
table=soup.select_one("div.nba-stat-table__overflow>table")
# print(table)
df=pd.read_html(str(table))
df[0].to_csv("all_players"+str(page_num)+".csv")
# driver.quit()
#定义选择下一页的数据
try:
next_page=driver.find_element_by_xpath('/html/body/main/div/div/div[2]/div/div/nba-stat-table/div[3]/div/div/a[2]')
next_page.click()
time.sleep(5)
if page_num<5:
page_num+=1
else:
pages_all=False
except Exception:
pages_all=False
结果截图
- 生成的文件
- 文件内容