中秋节马上就到了,和往年一样,月饼再次成为人们关心的话题,只不过越来越多的人开始吐槽,月饼似乎越来越贵了,如果这些成本花在了原材料上那还好。可惜的是,月饼贵的主要原因是因为月饼的包装越来越精美了,而不是原材料贵了,那么大家在购买月饼时更看重颜值还是性价比呢?
最近一段时间月饼的销量持续增长,各个厂家也推出了各个不同口味类别的月饼,价格差异也较大。面对口味众多,价格差异大的月饼,我们到底该如何选择呢?今天就一起用Python爬取某宝月饼信息,并对爬取的数据进行可视化分析,一起来看看哪种月饼最受欢迎,看看那些高价位的月饼真的有多少人购买。
首先我们先爬取数据,本文我们通过selenium模块进行月饼数据爬取。最近某宝的反爬也是超级严格的,面对封ip这个阻碍,这次我们是费了不少功夫测试了一家质量好的代理。
使用selenium模拟爬取数据示例如下:
from selenium import webdriver
import string
import zipfile
# 代理服务器(产品官网 www.16yun.cn)
proxyHost = "t.16yun.cn"
proxyPort = "3111"
# 代理验证信息
proxyUser = "username"
proxyPass = "password"
def create_proxy_auth_extension(proxy_host, proxy_port,
proxy_username, proxy_password,
scheme='http', plugin_path=None):
if plugin_path is None:
plugin_path = r'/tmp/{}_{}@t.16yun.zip'.format(proxy_username, proxy_password)
manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "16YUN Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
"""
background_js = string.Template(
"""
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "${scheme}",
host: "${host}",
port: parseInt(${port})
},
bypassList: ["localhost"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "${username}",
password: "${password}"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
"""
).substitute(
host=proxy_host,
port=proxy_port,
username=proxy_username,
password=proxy_password,
scheme=scheme,
)
print(background_js)
with zipfile.ZipFile(plugin_path, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
return plugin_path
proxy_auth_plugin_path = create_proxy_auth_extension(
proxy_host=proxyHost,
proxy_port=proxyPort,
proxy_username=proxyUser,
proxy_password=proxyPass)
option = webdriver.ChromeOptions()
option.add_argument("--start-maximized")
# 如报错 chrome-extensions
# option.add_argument("--disable-extensions")
option.add_extension(proxy_auth_plugin_path)
# 关闭webdriver的一些标志
# option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(
chrome_options=option,
executable_path="./chromdriver"
)
# 修改webdriver get属性
# script = '''
# Object.defineProperty(navigator, 'webdriver', {
# get: () => undefined
# })
# '''
# driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": script})
driver.get("https://uland.taobao.com/")
python获取Cookie
HtmlUnitDriver(Java)
Firefox(Java)
php-webdriver-chrome
我们可以读取已经清洗结束的数据,然后通过对店铺分组获取各个店铺的月饼销量数据,这样就可以为大家提供一个直观的数据分析图。大家在选购的时候也有个大概的了解。