爬取两年内到六安旅游人数并进行可视化源码
时间: 2024-06-08 10:07:51 浏览: 18
以下是使用Python爬取两年内到六安旅游人数并进行可视化的源代码:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
# 发送请求获取网页内容
def get_html(url):
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.36'}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
return response.text
# 解析网页内容获取数据
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
table = soup.find_all('table')[0]
data = pd.read_html(str(table))[0]
data = data.drop([0])
data.columns = ['date', 'num']
data['date'] = pd.to_datetime(data['date'])
data['num'] = pd.to_numeric(data['num'])
return data
# 绘制折线图
def plot_data(data):
plt.plot(data['date'], data['num'])
plt.xlabel('Date')
plt.ylabel('Number')
plt.title('Number of tourists in Lu'an')
plt.show()
if __name__ == '__main__':
url = 'http://www.luandj.gov.cn/html/zwgk/zwdt/2018/12/28/3b56d1e9-1b7d-42a7-b5c7-76f3212a3d38.html'
html = get_html(url)
data = parse_html(html)
plot_data(data)
```
代码解释:
1. 使用requests库发送请求获取网页内容。
2. 使用BeautifulSoup解析网页内容获取数据。
3. 使用pandas库将数据转换成DataFrame格式。
4. 使用matplotlib库绘制折线图。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)