(一) 分析网页
下载下面这个链接的销售数据
https://item.jd.com/6733026.html#comment
1, 翻页的时候, 谷歌 F12 的 Network 页签可以看到下面的请求.(这里的翻页指商品评价中 1,2,3 页等)
从 Preview 页签可以看出, 这个请求是获取评论信息的
2, 对比第一页, 第二页, 第三页... 请求 URL 的区别
可以发现 page=0,page=1,0 和 1 指的应该是页数.
第一页的 request url: 没有这个 rid=0& . 第二, 三页... 的 request url: 多了这个 rid=0&
除了上面这 2 个地方, 其他内容都是一样的.
3, 直接在浏览器输入 复制出来的 request url, 可以看到评论, 颜色, 版本, 内存信息, 代码将根据这些信息来写正则表达式进行匹配.
(二) 实现代码
delayed.py 的代码和我前面发的是一样的 (Python 网络爬虫笔记 (二)), 不限速的话把和这个模块相关的代码删除就行了
- import urllib.request as ure
- import urllib.parse
- import openpyxl
- import re
- import os
- from delayed import WaitFor
- def download(url,user_agent='FireDrich',num=2,proxy=None):
- print('下载:'+url)
- #设置用户代理
- headers = {'user_agent':user_agent}
- request = ure.Request(url,headers=headers)
- #支持代理
- opener = ure.build_opener()
- if proxy:
- proxy_params = {urllib.parse.urlparse(url).scheme: proxy}
- opener.add_handler(ure.ProxyHandler(proxy_params))
- try:
- #下载网页
- # html = ure.urlopen(request).read()
- html = opener.open(request).read()
- except ure.URLError as e:
- print('下载失败'+e.reason)
- html=None
- if num>0:
- #遇到 5XX 错误时, 递归调用自身重试下载, 最多重复 2 次
- if hasattr(e,'code') and 500<=e.code<600:
- return download(url,num=num-1)
- return html
- def writeXls(sale_list):
- #如果 Excel 不存在, 创建 Excel, 否则直接打开已经存在文档
- if 'P20 销售情况. xlsx' not in os.listdir():
- wb =openpyxl.Workbook()
- else:
- wb =openpyxl.load_workbook('P20 销售情况. xlsx')
- sheet = wb['Sheet']
- sheet['A1'] = '颜色'
- sheet['B1'] = '版本'
- sheet['C1'] = '内存'
- sheet['D1'] = '评论'
- sheet['E1'] = '评论时间'
- x = 2
- #迭代所有销售信息 (列表)
- for s in sale_list:
- #获取颜色等信息
- content = s[0]
- creationTime = s[1]
- productColor = s[2]
- productSize = s[3]
- saleValue = s[4]
- # 将颜色等信息添加到 Excel
- sheet['A' + str(x)] = productColor
- sheet['B' + str(x)] = productSize
- sheet['C' + str(x)] = saleValue
- sheet['D' + str(x)] = content
- sheet['E' + str(x)] = creationTime
- x += 1
wb.save('P20 销售情况. xlsx')
- page = 0
- allSale =[]
- waitFor = WaitFor(2)
- #预编译匹配颜色, 版本, 内存等信息的正则表达式
- regex = re.compile('"content":"(.*?)","creationTime":"(.*?)".*?"productColor":"(.*?)","productSize":"(.*?)".*?"saleValue":"(.*?)"')
- #这里只下载 20 页数据, 可以设置大一些 (因为就算没评论信息, 也能下载到一些标签信息等, 所以可以 if 正则没匹配的话就结束循环, 当然, 下面没处理这个)
- while page<20:
- if page==0:
- url = 'https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98vv176&productId=6733026&score=0&sortType=5&page=' + str(page) + '&pageSize=10&isShadowSku=0&fold=1'
- else:
- url = 'https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98vv176&productId=6733026&score=0&sortType=5&page=' + str(page) + '&pageSize=10&isShadowSku=0&rid=0&fold=1'
- waitFor.wait(url)
- html = download(url)
- html = html.decode('GBK')
- #以列表形式返回颜色, 版本, 内存等信息
- sale = regex.findall(html)
- #将颜色, 版本, 内存等信息添加到 allSale 中 (扩展 allSale 列表)
- allSale.extend(sale)
- page += 1
- writeXls(allSale)
(三) 数据分析
1, 下载后的数据如下图所示.
2, 生成图表.
来源: https://www.cnblogs.com/simple-free/p/8884098.html