python爬取NBA东西部数据
时间: 2024-06-01 20:05:27 浏览: 168
python毕设篮球NBA全站爬取测试
可以使用Python中的requests和BeautifulSoup库来实现爬取NBA东西部数据。
首先,需要用requests库获取NBA官网的网页源代码,然后使用BeautifulSoup库解析网页内容,从而获取所需的数据。以下是一个简单的爬取NBA东部排名的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.nba.com/standings/team-record-by-conference'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
eastern_conference_table = soup.find('table', {'class': 'standings__table--conference', 'data-conference': 'east'})
eastern_teams = eastern_conference_table.tbody.find_all('tr')
for team in eastern_teams:
name = team.find('td', {'class': 'team__name'}).a.text
rank = team.find('td', {'class': 'team__rank'}).text
record = team.find('td', {'class': 'team__record'}).text
print(f'{rank}. {name} - {record}')
```
在上述代码中,我们首先使用requests库获取NBA官网东部排名页面的源代码,然后使用BeautifulSoup库解析源代码,找到包含东部排名表格的HTML元素,最后提取表格中的球队名称、排名和战绩信息。最终输出结果为:
```
1. Philadelphia 76ers - 49-23
2. Brooklyn Nets - 48-24
3. Milwaukee Bucks - 46-26
4. New York Knicks - 41-31
5. Atlanta Hawks - 41-31
6. Miami Heat - 40-32
7. Boston Celtics - 36-36
8. Washington Wizards - 34-38
9. Indiana Pacers - 34-38
10. Charlotte Hornets - 33-39
11. Toronto Raptors - 27-45
12. Chicago Bulls - 31-41
13. Cleveland Cavaliers - 22-50
14. Orlando Magic - 21-51
15. Detroit Pistons - 20-52
```
阅读全文