前言
嗨喽~大家好呀,这里是魔王呐 !
-
python 3.6
-
pycharm
-
csv
-
requests >>> pip install requests
-
parsel
- win + R 输入 cmd 点击确定, 输入安装命令 pip install 模块名 (pip install requests) 回车
- 在pycharm中点击Terminal(终端) 输入安装命令
-
pyecharts
-
pandas
-
确定一下目标需求: 爬取猫咪交易网站数据 做一个数据可视化图
-
去网站 : 地区 …
-
如果想要在网页上抓包 找一些数据来源 都是要通过开发者工具 F12/ 鼠标右键点击检查
- 可以直接复制想要数据内容在开发者工具进行搜索
-
请求 http://www.maomijiaoyi.com/index.php?/chanpinliebiao_c_2.html 获取 猫咪的详情页url地址以及地区
-
请求 猫咪的详情页url地址 获取猫咪详情信息数据
-
保存数据 到CSV文件
-
数据可视化
获取源码链接点击
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()
for page in range(1, 21):
print(f'===========================正在爬取第{page}页的数据内容==================================')
请求头: 把python代码伪装成 浏览器对服务器发送请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'
}
response = requests.get(url=url, headers=headers)
获取网页的文本数据 response.text json()
获取json字典数据
# print(response.text)
# 解析数据 获取 猫咪的详情页url地址以及地区
# 要把 网页文本数据转换成 parsel 解析的 对象
selector = parsel.Selector(response.text)
href = selector.css('div.content:nth-child(1) a::attr(href)').getall()
areas = selector.css('div.content:nth-child(1) .area .color_333::text').getall()
# 列表推导式
areas = [i.strip() for i in areas]
# 需要把两个列表合成一个列表 遍历循环提取每一个元素
zip_data = zip(href, areas)
for index in zip_data:
css选择器: 根据标签提取数据内容
getall()
返回的是列表
get()
是返回的字符串
response_1 = requests.get(url=index_url, headers=headers)
selector_1 = parsel.Selector(response_1.text)
area = index[1]
# 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=' | ')
获取源码链接点击
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)
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 Faker
c = (
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 TreeMap
pingzhong = 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 SymbolType
location = 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 s
s = int(s)
if 1
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?