爬取历届冬奥会数据代码
时间: 2023-10-05 11:12:30 浏览: 156
以下是一个使用Python和BeautifulSoup库爬取历届冬奥会数据的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 发送请求并获取网页内容
url = 'https://www.sports-reference.com/olympics/winter/'
response = requests.get(url)
content = response.content
# 解析网页内容
soup = BeautifulSoup(content, 'html.parser')
tables = soup.find_all('table', {'class': 'stats_table'})
# 遍历所有表格
for table in tables:
# 获取表格标题
title = table.find_previous_sibling('h2').text.strip()
print('Table:', title)
# 获取表头
headers = []
ths = table.find_all('th')
for th in ths:
headers.append(th.text.strip())
print(headers)
# 获取表格数据
rows = table.find_all('tr')
for row in rows:
data = []
tds = row.find_all('td')
for td in tds:
data.append(td.text.strip())
if data:
print(data)
```
这段代码将会爬取历届冬奥会的各种数据,并以表格的形式输出。你可以根据自己的需求进行修改和扩展。
阅读全文