用Python写一个爬去NBA球员薪资数据的程序
时间: 2023-05-26 20:03:42 浏览: 172
以下是使用Python爬取NBA球员薪资数据的示例程序:
```python
import requests
from bs4 import BeautifulSoup
import csv
# 请求URL
url = 'https://www.spotrac.com/nba/rankings/'
# 发送HTTP请求
response = requests.get(url)
# 解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')
# 获取表格头部信息
table_header = soup.find_all('thead')[0].find_all('th')
header = []
for th in table_header:
header.append(th.text.strip())
# 获取表格内容信息
table_body = soup.find_all('tbody')[0].find_all('tr')
data = []
for tr in table_body:
row = []
td_list = tr.find_all('td')
for td in td_list:
row.append(td.text.strip())
data.append(row)
# 写入CSV文件
with open('nba_salary_data.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(header)
writer.writerows(data)
```
运行程序后,将在当前目录下生成一个名为“nba_salary_data.csv”的CSV文件,其中包含了当前NBA球员的薪资数据。可以使用Excel等软件打开此文件,查看相关信息。
阅读全文