Python爬取百合网用户数据并可视化分析男女年龄分布
由于百合网需要登录才能查看数据,因此本文无法直接爬取数据。以下是一个假设的数据可视化过程,数据来源为百合网每日推荐的用户信息。
首先,我们需要使用Python爬虫程序获取百合网每日推荐的用户信息。这里我们使用requests和BeautifulSoup库。
import requests
from bs4 import BeautifulSoup
url = 'https://www.baihe.com/today/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
接下来,我们需要从网页中提取所需的数据。例如,我们可以获取用户的性别和年龄。
users = soup.select('.user-info')
age_list = []
gender_list = []
for user in users:
gender = user.select_one('.icon-gender').get('class')[1]
age = user.select_one('.age').text
age_list.append(int(age))
if gender == 'icon-gender-male':
gender_list.append('male')
else:
gender_list.append('female')
最后,我们可以使用matplotlib库进行数据可视化。
import matplotlib.pyplot as plt
# 将年龄分段
bins = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# 绘制男女年龄分布直方图
plt.hist([age_list[i] for i in range(len(age_list)) if gender_list[i] == 'male'], bins=bins, alpha=0.5, label='male')
plt.hist([age_list[i] for i in range(len(age_list)) if gender_list[i] == 'female'], bins=bins, alpha=0.5, label='female')
plt.legend(loc='upper right')
plt.xlabel('Age')
plt.ylabel('Count')
plt.show()
这样就可以绘制出百合网每日推荐用户的男女年龄分布直方图了。
原文地址: https://www.cveoy.top/t/topic/o0ir 著作权归作者所有。请勿转载和采集!