python爬取全球幸福指数数据代码
时间: 2023-10-03 08:05:15 浏览: 40
以下是一个简单的 Python 爬虫程序,用于爬取全球幸福指数数据:
```python
import requests
from bs4 import BeautifulSoup
import csv
# 设置请求头信息
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 发送请求
url = 'https://www.worldometers.info/world-population/population-by-country/'
response = requests.get(url, headers=headers)
# 解析网页
soup = BeautifulSoup(response.text, 'html.parser')
# 提取数据
table = soup.find('table', attrs={'class': 'table table-striped'})
rows = table.find_all('tr')
# 将数据保存到 CSV 文件中
with open('world_population.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Country', 'Population'])
for row in rows[1:]:
cols = row.find_all('td')
country = cols[1].text.strip()
population = cols[2].text.strip().replace(',', '')
writer.writerow([country, population])
```
以上代码可以爬取 https://www.worldometers.info/world-population/population-by-country/ 网站上的全球人口数据,并将数据保存到 `world_population.csv` 文件中。你可以根据自己的需求修改代码,例如更改请求的 URL、修改数据保存的文件名等等。