python爬虫可视化案例
时间: 2023-07-11 19:00:41 浏览: 133
Python爬虫可视化可以用来将爬取到的数据以图形化的方式展示出来,这样可以更加直观地观察到数据的变化和趋势。
以下是一个Python爬虫可视化案例:
1. 爬取数据
首先,我们需要通过Python爬虫爬取一些数据,例如豆瓣电影的评分和评论数。我们可以使用requests和BeautifulSoup库来实现:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/top250'
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'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
movies = []
for movie in soup.find_all('div', class_='info'):
title = movie.find('span', class_='title').text
rating_num = movie.find('span', class_='rating_num').text
comment_num = movie.find('div', class_='star').find_all('span')[3].text[:-3]
movies.append({'title': title, 'rating_num': rating_num, 'comment_num': comment_num})
```
2. 可视化数据
接下来,我们可以使用matplotlib库将爬取到的数据可视化出来:
```python
import matplotlib.pyplot as plt
x = [movie['title'] for movie in movies]
y1 = [float(movie['rating_num']) for movie in movies]
y2 = [int(movie['comment_num']) for movie in movies]
fig, ax1 = plt.subplots()
ax1.bar(x, y1, color='tab:blue')
ax1.set_xlabel('Movie Title')
ax1.set_ylabel('Rating')
ax2 = ax1.twinx()
ax2.plot(x, y2, color='tab:red')
ax2.set_ylabel('Comment Number')
plt.show()
```
这段代码将评分以柱状图的形式展示出来,评论数以折线图的形式展示出来。通过这种方式,我们可以更加直观地观察到每部电影的评分和评论数之间的关系。
阅读全文