前言
嗨嘍,大家好呀~這里是愛看美女的茜茜吶
開發(fā)環(huán)境:
首先我們先來安裝一下寫代碼的軟件(對沒安裝的小白說)
-
Python 3.8 / 編譯器
-
Pycharm 2021.2版本 / 編輯器
-
專業(yè)版是付費(fèi)的 <文章下方名片可獲取魔法永久用~>
-
社區(qū)版是免費(fèi)的
-
第三方模塊使用:
-
requests >>> pip install requests 數(shù)據(jù)請求
-
parsel >>> pip install parsel 數(shù)據(jù)解析
-
csv <表格文件> 內(nèi)置模塊 保存數(shù)據(jù)
python第三方模塊安裝:
-
win + R 輸入 cmd 點(diǎn)擊確定, 輸入安裝命令 pip install 模塊名 (pip install requests) 回車
-
在pycharm中點(diǎn)擊Terminal(終端) 輸入安裝命令
(如果你覺得安裝速度比較慢, 你可以切換國內(nèi)鏡像源)
代碼步驟:
-
發(fā)送請求
-
獲取數(shù)據(jù)
-
解析數(shù)據(jù)
-
保存數(shù)據(jù)
python資料、源碼、教程: 點(diǎn)擊此處跳轉(zhuǎn)文末名片獲取
采集代碼展示:
# 導(dǎo)入數(shù)據(jù)請求模塊 --> 第三方模塊, 需要安裝 pip install requests
import requests
# 導(dǎo)入數(shù)據(jù)解析模塊 --> 第三方模塊, 需要安裝 pip install parsel
import parsel
# 導(dǎo)入csv模塊
import csv
for page in range(1, 26):
請求鏈接
url = f'http://****m/books/bestsellers/01.00.00.00.00.00-recent30-0-0-1-{page}'
偽裝 模擬 --> 請求頭 字典數(shù)據(jù)類型
headers = {
# User-Agent 用戶代理 表示瀏覽器基本身份信息
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36'
}
發(fā)送請求 等號左邊都是自定義變量名
response = requests.get(url=url, headers=headers)
selector = parsel.Selector(response.text)
第一次提取 獲取所有書籍所對應(yīng)li標(biāo)簽
lis = selector.css('.bang_list_mode li')
for循環(huán)遍歷
for li in lis:
“”"
提取具體數(shù)據(jù)信息
css選擇器 --> 可以直接復(fù)制粘貼就好了
get 獲取第一個標(biāo)簽數(shù)據(jù)內(nèi)容
“”"
title = li.css('.name a::attr(title)').get() # 書名
star = li.css('.star a::text').get() # 評論
recommend = li.css('.tuijian::text').get() # 推薦
writer = li.css('.publisher_info a::text').get() # 作者
date = li.css('.publisher_info span::text').get() # 時間
publisher = li.css('div:nth-child(6) a::text').get() # 出版社
price_n = li.css('.price .price_n::text').get() # 售價
price_r = li.css('.price .price_r::text').get() # 原價
price_s = li.css('.price .price_s::text').get() # 折扣
price_e = li.css('.price_e .price_n::text').get() # 電子書
href = li.css('.name a::attr(href)').get() # 詳情頁
創(chuàng)建字典
dit = {
'書名': title,
'評論': star,
'推薦': recommend,
'作者': writer,
'時間': date,
'出版社': publisher,
'售價': price_n,
'原價': price_r,
'折扣': price_s,
'電子書': price_e,
'詳情頁': href,
}
csv_writer.writerow(dit)
print(title, star, recommend, writer, date, publisher, price_n, price_r, price_s, price_e, href)
創(chuàng)建表格保存數(shù)據(jù)
f = open('書籍.csv', mode='a', encoding='utf-8', newline='')
csv_writer = csv.DictWriter(f, fieldnames=[
'書名',
'評論',
'推薦',
'作者',
'時間',
'出版社',
'售價',
'原價',
'折扣',
'電子書',
'詳情頁',
])
寫入表頭
csv_writer.writeheader()
可視化代碼展示:
1.導(dǎo)入模塊
import pandas as pd
from pyecharts.charts import *
from pyecharts.globals import ThemeType#設(shè)定主題
from pyecharts.commons.utils import JsCode
import pyecharts.options as opts
2.導(dǎo)入數(shù)據(jù)
df = pd.read_csv('data.csv', encoding='utf-8', engine='python')
df.head()
3.數(shù)據(jù)處理
df['書名'] = df['書名'].apply(lambda x:x.split('(')[0])
df.head()
df['書籍簡介'] = df['書名'].str.extract('.*?((.*?))')
df['書籍簡介'].fillna('無', inplace=True)
df.head(1)
提取評論數(shù)
data = df.apply(lambda x:x['評論'].split('條評論')[0], axis=1)
df['評論數(shù)'] = data.astype('int64')
df.head(1)
原價、售價、電子書價格 數(shù)值化
df['原價'] = df['原價'].str.replace('¥', '')
df['售價'] = df['售價'].str.replace('¥', '')
df['電子書價格'] = df['電子書'].str.replace('¥', '')
df.head(1)
df.info()
df['原價'] = df['原價'].str.replace(',', '').astype('float64')
df['售價'] = df['售價'].str.replace(',', '').astype('float64')
缺失值
電子書價格列額外處理
4.數(shù)據(jù)可視化
書籍總體價格區(qū)間
def tranform_price(x):
if x <= 50.0:
return '0~50元'
elif x <= 100.0:
return '51~100元'
elif x <= 500.0:
return '101~500元'
elif x <= 1000.0:
return '501~1000元'
else:
return '1000以上'
df['價格分級'] = df['原價'].apply(lambda x:tranform_price(x))
price_1 = df['價格分級'].value_counts()
datas_pair_1 = [(i, int(j)) for i, j in zip(price_1.index, price_1.values)]
df['售價價格分級'] = df['售價'].apply(lambda x:tranform_price(x))
price_2 = df['售價價格分級'].value_counts()
datas_pair_2 = [(i, int(j)) for i, j in zip(price_2.index, price_2.values)]
pie1 = (
Pie(init_opts=opts.InitOpts(theme='dark',width='1000px',height='600px'))
.add('', datas_pair_1, radius=['35%', '60%'])
.set_series_opts(label_opts=opts.LabelOpts(formatter=":n5n3t3z%"))
.set_global_opts(
title_opts=opts.TitleOpts(
title="書籍\n\n原價價格區(qū)間",
pos_left='center',
pos_top='center',
title_textstyle_opts=opts.TextStyleOpts(
color='#F0F8FF',
font_size=20,
font_weight='bold'
),
)
)
.set_colors(['#EF9050', '#3B7BA9', '#6FB27C', '#FFAF34', '#D8BFD8', '#00BFFF', '#7FFFAA'])
)
pie1.render_notebook()
pie1 = (
Pie(init_opts=opts.InitOpts(theme='dark',width='1000px',height='600px'))
.add('', datas_pair_2, radius=['35%', '60%'])
.set_series_opts(label_opts=opts.LabelOpts(formatter=":n5n3t3z%"))
.set_global_opts(
title_opts=opts.TitleOpts(
title="書籍\n\n售價價格區(qū)間",
pos_left='center',
pos_top='center',
title_textstyle_opts=opts.TextStyleOpts(
color='#F0F8FF',
font_size=20,
font_weight='bold'
),
)
)
.set_colors(['#EF9050', '#3B7BA9', '#6FB27C', '#FFAF34', '#D8BFD8', '#00BFFF', '#7FFFAA'])
)
pie1.render_notebook()
各個出版社書籍?dāng)?shù)量柱狀圖
counts = df.groupby('出版社')['書名'].count().sort_values(ascending=False).head(20)
bar=(
Bar(init_opts=opts.InitOpts(height='500px',width='1000px',theme='dark'))
.add_xaxis(counts.index.tolist())
.add_yaxis(
'出版社書籍?dāng)?shù)量',
counts.values.tolist(),
label_opts=opts.LabelOpts(is_show=True,position='top'),
itemstyle_opts=opts.ItemStyleOpts(
color=JsCode("""new echarts.graphic.LinearGradient(
0, 0, 0, 1,[{offset: 0,color: 'rgb(255,99,71)'}, {offset: 1,color: 'rgb(32,178,170)'}])
"""
)
)
)
.set_global_opts(
title_opts=opts.TitleOpts(
title='各個出版社書籍?dāng)?shù)量柱狀圖'),
xaxis_opts=opts.AxisOpts(name='書籍名稱',
type_='category',
axislabel_opts=opts.LabelOpts(rotate=90),
),
yaxis_opts=opts.AxisOpts(
name='數(shù)量',
min_=0,
max_=29.0,
splitline_opts=opts.SplitLineOpts(is_show=True,linestyle_opts=opts.LineStyleOpts(type_='dash'))
),
tooltip_opts=opts.TooltipOpts(trigger='axis',axis_pointer_type='cross')
)
.set_series_opts(
markline_opts=opts.MarkLineOpts(
data=[
opts.MarkLineItem(type_='average',name='均值'),
opts.MarkLineItem(type_='max',name='最大值'),
opts.MarkLineItem(type_='min',name='最小值'),
]
)
)
)
bar.render_notebook()
電子書版本占比
per = df['電子書'].value_counts()['無電子書版本']/len(df)
c = (
Liquid()
.add("lq", [1-per], is_outline_show=False)
.set_global_opts(title_opts=opts.TitleOpts(title="電子書版本占比"))
)
c.render_notebook()
bar=(
Bar(init_opts=opts.InitOpts(height='500px',width='1000px',theme='dark'))
.add_xaxis(price_top.index.tolist())
.add_yaxis(
'書籍單價',
price_top.values.tolist(),
label_opts=opts.LabelOpts(is_show=True,position='top'),
itemstyle_opts=opts.ItemStyleOpts(
color=JsCode("""new echarts.graphic.LinearGradient(
0, 0, 0, 1,[{offset: 0,color: 'rgb(255,99,71)'}, {offset: 1,color: 'rgb(32,178,170)'}])
"""
)
)
)
.set_global_opts(
title_opts=opts.TitleOpts(
title='單價最高的書籍詳細(xì)柱狀圖'),
xaxis_opts=opts.AxisOpts(name='書籍名稱',
type_='category',
axislabel_opts=opts.LabelOpts(rotate=90),
),
yaxis_opts=opts.AxisOpts(
name='單價/元',
min_=0,
max_=1080.0,
splitline_opts=opts.SplitLineOpts(is_show=True,linestyle_opts=opts.LineStyleOpts(type_='dash'))
),
tooltip_opts=opts.TooltipOpts(trigger='axis',axis_pointer_type='cross')
)
.set_series_opts(
markline_opts=opts.MarkLineOpts(
data=[
opts.MarkLineItem(type_='average',name='均值'),
opts.MarkLineItem(type_='max',name='最大值'),
opts.MarkLineItem(type_='min',name='最小值'),
]
)
)
)
bar.render_notebook()
import pyecharts.options as opts
from pyecharts.charts import Pie
“”"
目前無法實(shí)現(xiàn)的功能:
1、迷之顏色映射的問題
“”"
content = df['出版社'].value_counts()
# x = content.index.tolist()[:10]
# y = content.values.tolist()[:10]
x_data = content.index.tolist()[:10]
y_data = content.values.tolist()[:10]
data_pair = [list(z) for z in zip(x_data, y_data)]
data_pair.sort(key=lambda x: x[1])
c = (
Pie(init_opts=opts.InitOpts(width="1600px", height="800px", bg_color="#2c343c"))
.add(
series_name="訪問來源",
data_pair=data_pair,
rosetype="radius",
radius="55%",
center=["50%", "50%"],
label_opts=opts.LabelOpts(is_show=False, position="center"),
)
.set_global_opts(
title_opts=opts.TitleOpts(
title="前10出版社, 書籍占比",
pos_left="center",
pos_top="20",
title_textstyle_opts=opts.TextStyleOpts(color="#fff"),
),
legend_opts=opts.LegendOpts(is_show=False),
)
.set_series_opts(
tooltip_opts=opts.TooltipOpts(
trigger="item", formatter="{a} <br/>: {c} (n5n3t3z%)"
),
label_opts=opts.LabelOpts(color="rgba(255, 255, 255, 0.3)"),
)
)
c.render_notebook()
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.faker import Faker
content = df['出版社'].value_counts() # 讀取出版社的數(shù)據(jù)
x_data = content.index.tolist()[:10]
y_data = content.values.tolist()[:10]
data_pair = [list(z) for z in zip(x_data, y_data)]
data_pair
# x_data = content.index.tolist()[:10] #
# y_data = content.values.tolist()[:10]
# data_pair = [list(z) for z in zip(x_data, y_data)]
c = (
Pie()
.add(
"",
data_pair,
radius=["40%", "75%"],
)
.set_global_opts(
title_opts=opts.TitleOpts(title="出版社前10名"),
legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"),
)
.set_series_opts(label_opts=opts.LabelOpts(formatter=": {c}"))
)
c.render_notebook()
尾語
感謝你觀看我的文章吶~本次航班到這里就結(jié)束啦 ??
希望本篇文章有對你帶來幫助 ??,有學(xué)習(xí)到一點(diǎn)知識~
躲起來的星星??也在努力發(fā)光,你也要努力加油(讓我們一起努力叭)。
文章來源:http://www.zghlxwxcb.cn/news/detail-441301.html
最后,宣傳一下呀~??????更多源碼、資料、素材、解答、交流皆點(diǎn)擊下方名片獲取呀??????文章來源地址http://www.zghlxwxcb.cn/news/detail-441301.html
到了這里,關(guān)于當(dāng)~python批量獲取某電商:商品數(shù)據(jù)并作可視化的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!