Python采集猫咪数据并做数据可视化图

编程入门 行业动态 更新时间:2024-10-24 14:25:33

Python采集猫咪<a href=https://www.elefans.com/category/jswz/34/1771445.html style=数据并做数据可视化图"/>

Python采集猫咪数据并做数据可视化图

前言 😋

大家早好、午好、晚好吖~

猫咪这种生物,你经常在广大平台上刷到,在同事、朋友那里看到~

这么可爱得东西,一下就激起了你的rua毛冲动,甚至还想自己养一只

那么今天我们就来采集一下猫咪数据并做个数据可视化~~

GOGOGO!!!出发~

环境介绍:

  • python 3.6

  • pycharm

模块

采集部分使用模块:

  • csv

  • requests >>> pip install requests

  • parsel

数据可视化使用模块:

  • pyecharts

  • pandas

如果安装python第三方模块:

  1. win + R 输入 cmd 点击确定, 输入安装命令 pip install 模块名 (pip install requests) 回车

  2. 在pycharm中点击Terminal(终端) 输入安装命令

+python安装包 安装教程视频
+pycharm 社区版 专业版 及 激活码免费 找助理小姐姐 V : python10010免费领

本次的案例流程思路:

一. 网站数据来源查询:

二. 代码实现步骤


采集代码

导入模块

import requests  # 第三方模块 需要 pip install requests 发送请求
import parsel # 解析模块 pip install parsel
import csv # 内置模块 不需要大家安装
f = open('猫咪.csv', mode='a', encoding='utf-8', newline='')
csv_writer = csv.DictWriter(f, fieldnames=['地区', '店名', '标题', '价格', '浏览次数', '卖家承诺', '在售只数','年龄', '品种', '预防', '联系人', '联系方式', '异地运费', '是否纯种','猫咪性别', '驱虫情况', '能否视频', '详情页'])# 写入表头
csv_writer.writeheader()

    response = requests.get(url=url, headers=headers)# 获取网页的文本数据  response.text  json() 获取json字典数据# print(response.text)# 解析数据 获取 猫咪的详情页url地址以及地区# 1. 要把 网页文本数据转换成 parsel 解析的 对象selector = parsel.Selector(response.text)# css选择器: 根据标签提取数据内容href = selector.css('div.content:nth-child(1) a::attr(href)').getall()# getall() 返回的是列表   get() 是返回的字符串areas = selector.css('div.content:nth-child(1) .area .color_333::text').getall()# 列表推导式areas = [i.strip() for i in areas]

        # get() 取一个  返回是字符串  strip() 字符串的方法title = selector_1.css('.detail_text .title::text').get().strip() # 标题shop = selector_1.css('.dinming::text').get().strip() # 店名price = selector_1.css('.info1 div:nth-child(1) span.red.size_24::text').get() # 价格views = selector_1.css('.info1 div:nth-child(1) span:nth-child(4)::text').get() # 浏览次数# replace() 替换promise = selector_1.css('.info1 div:nth-child(2) span::text').get().replace('卖家承诺: ', '') # 浏览次数num = selector_1.css('.info2 div:nth-child(1) div.red::text').get() # 在售只数age = selector_1.css('.info2 div:nth-child(2) div.red::text').get() # 年龄kind = selector_1.css('.info2 div:nth-child(3) div.red::text').get() # 品种prevention = selector_1.css('.info2 div:nth-child(4) div.red::text').get() # 预防person = selector_1.css('div.detail_text .user_info div:nth-child(1) .c333::text').get() # 联系人phone = selector_1.css('div.detail_text .user_info div:nth-child(2) .c333::text').get() # 联系方式postage = selector_1.css('div.detail_text .user_info div:nth-child(3) .c333::text').get().strip() # 包邮purebred = selector_1.css('.xinxi_neirong div:nth-child(1) .item_neirong div:nth-child(1) .c333::text').get().strip() # 是否纯种sex = selector_1.css('.xinxi_neirong div:nth-child(1) .item_neirong div:nth-child(4) .c333::text').get().strip() # 猫咪性别video = selector_1.css('.xinxi_neirong div:nth-child(2) .item_neirong div:nth-child(4) .c333::text').get().strip() # 能否视频worming = selector_1.css('.xinxi_neirong div:nth-child(2) .item_neirong div:nth-child(2) .c333::text').get().strip() # 是否驱虫dit = {'地区': area,'店名': shop,'标题': title,'价格': price,'浏览次数': views,'卖家承诺': promise,'在售只数': num,'年龄': age,'品种': kind,'预防': prevention,'联系人': person,'联系方式': phone,'异地运费': postage,'是否纯种': purebred,'猫咪性别': sex,'驱虫情况': worming,'能否视频': video,}csv_writer.writerow(dit)print(title, area, shop, price, views, promise, num, age,kind, prevention, person, phone, postage, purebred, sex, video, worming, index_url, sep=' | ')

效果


数据可视化代码

源码、解答、教程加Q裙:261823976 点击蓝字加入【python学习裙】

import pandas as pd 
pd.set_option('display.max_columns', None)
cat_info = pd.read_csv(r'C:\Users\青灯教育\Desktop\代码\猫咪.csv', encoding='utf-8', engine='python')
cat_info.head(5)

from pyecharts import options as opts
from pyecharts.charts import WordCloud
from pyecharts.globals import SymbolType
from pyecharts.globals import ThemeTypewords = [(i,1) for i in cat_info['品种'].unique()]
c = (WordCloud(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)).add("", words,shape=SymbolType.DIAMOND).set_global_opts(title_opts=opts.TitleOpts(title=""))
)
c.render('a.html')
cat_info['地区'] = cat_info['地区'].astype(str)
cat_info['province'] = cat_info['地区'].map(lambda s: s.split('/')[0])
pv = cat_info['province'].value_counts().reset_index()
from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Fakerc = (Map(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)).add("", [list(z) for z in zip(list(pv['index']), list(pv['province']))], "china").set_global_opts(title_opts=opts.TitleOpts(title="猫猫售卖省份分布"),visualmap_opts=opts.VisualMapOpts(max_=16500, is_piecewise=True),)
)c.render_notebook()

# 交易品种占比树状图
from pyecharts import options as opts
from pyecharts.charts import TreeMappingzhong = cat_info['品种'].value_counts().reset_index()
data = [{'value':i[1],'name':i[0]} for i in zip(list(pingzhong['index']),list(pingzhong['品种']))]c = (TreeMap(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)).add("", data).set_global_opts(title_opts=opts.TitleOpts(title="")).set_series_opts(label_opts=opts.LabelOpts(position="inside"))
)c.render_notebook()

# 
price = cat_info.groupby('品种').mean()['价格'].reset_index()
price['价格'] = round(price['价格'],0)
price = price.sort_values(by='价格')
from pyecharts import options as opts
from pyecharts.charts import PictorialBar
from pyecharts.globals import SymbolTypelocation = list(price['品种'])
values = list(price['价格'])c = (PictorialBar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)).add_xaxis(location).add_yaxis("",values,label_opts=opts.LabelOpts(is_show=False),symbol_size=18,symbol_repeat="fixed",symbol_offset=[0, 0],is_symbol_clip=True,symbol=SymbolType.ROUND_RECT,).reversal_axis().set_global_opts(title_opts=opts.TitleOpts(title="均价排名"),xaxis_opts=opts.AxisOpts(is_show=False),yaxis_opts=opts.AxisOpts(axistick_opts=opts.AxisTickOpts(is_show=False),axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(opacity=0),),),).set_series_opts(label_opts=opts.LabelOpts(position='insideRight'))
)c.render_notebook()

# 年龄分布,柱状图
cat_info['年龄'] = cat_info['年龄'].astype(str)
age = cat_info['年龄'].map(lambda x: x.replace('个月','')).reset_index()
def ages(s):if s == 'nan':return ss = int(s)if 1 <= s < 3: return '1-3个月'if 3 <= s < 6: return '3-6个月'if 6 <= s < 9:return '6-9个月'if 9 <= s < 12 :return '9-12个月'if s >= 12:return '1年以上'
age['age'] = age['年龄'].map(ages)
age = age['age'].value_counts().reset_index()
age = age[age['index'] != 'nan']

from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Fakerx = ['1-3个月','3-6个月','6-9个月','9-12个月','1年以上']
y = [69343,115288,18239,4139,5]c = (Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)).add_xaxis(x).add_yaxis('', y).set_global_opts(title_opts=opts.TitleOpts(title="猫龄分布"))
)c.render_notebook()

## 浏览次数是否跟价格成正比,散点图
view = cat_info['浏览次数']
money = cat_info['价格']import pyecharts.options as opts
from pyecharts.charts import Scatterx_data = list(view)[:1000]
y_data = list(money)[:1000]c = (Scatter(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)).add_xaxis(xaxis_data=x_data).add_yaxis(series_name="",y_axis=y_data,symbol_size=20,label_opts=opts.LabelOpts(is_show=False),).set_series_opts().set_global_opts(xaxis_opts=opts.AxisOpts(type_="value", splitline_opts=opts.SplitLineOpts(is_show=True),name='浏览次数'),yaxis_opts=opts.AxisOpts(type_="value",axistick_opts=opts.AxisTickOpts(is_show=True),splitline_opts=opts.SplitLineOpts(is_show=True),name='价格'),tooltip_opts=opts.TooltipOpts(is_show=False),)
)c.render_notebook()

from pyecharts import options as opts
from pyecharts.charts import Boxplotv1 = [list(a_p[a_p['age'] == '1-3个月']['价格']),list(a_p[a_p['age'] == '3-6个月']['价格']),list(a_p[a_p['age'] == '6-9个月']['价格']),list(a_p[a_p['age'] == '9-12个月']['价格']),list(a_p[a_p['age'] == '1年以上']['价格'])
]c = Boxplot(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
c.add_xaxis(["1-3个月", "3-6个月",'6-9个月','9-12个月','1年以上'])
c.add_yaxis("喵喵", c.prepare_data(v1))
c.set_global_opts(title_opts=opts.TitleOpts(title="猫龄&价格"))c.render_notebook()

# 价格是否与预防有关,箱型图
yufang = cat_info[['价格','预防']]
yufang['预防'].unique()

from pyecharts import options as opts
from pyecharts.charts import Boxplotv1 = [list(yufang[yufang['预防'] == '0针疫苗']['价格']),list(yufang[yufang['预防'] == '1针疫苗']['价格']),list(yufang[yufang['预防'] == '2针疫苗']['价格']),list(yufang[yufang['预防'] == '3针疫苗']['价格']),
]c = Boxplot(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
c.add_xaxis(["0针疫苗", "1针疫苗",'2针疫苗','3针疫苗'])
c.add_yaxis("喵喵", c.prepare_data(v1))
c.set_global_opts(title_opts=opts.TitleOpts(title="防疫&价格"))c.render_notebook()

尾语 💝

好了,我的这篇文章写到这里就结束啦!

有更多建议或问题可以评论区或私信我哦!一起加油努力叭(ง •_•)ง

喜欢就关注一下博主,或点赞收藏评论一下我的文章叭!!!

更多推荐

Python采集猫咪数据并做数据可视化图

本文发布于:2024-03-05 05:16:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1711404.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   猫咪   并做   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!