这个实例是从淘宝爬数据,原文是:http://www.cnblogs.com/nima/p/5324490.html
因为我比较关心的是网络这一块,所以对文章做了很多删改。侧重在理解request、cookie两个模块
至于如何把数据保存到excel,怎么排版,这些是完全没有意义的,不是正式生产环境,做得多么漂亮都没意义。

这次用了很多新的模块或概念:
图像相关的库Pillow,
下载地址 点击打开链接
原文的是把图片链接写到excel里面的,我改了之后就没有了,只是下载下来。

Mozilla:
经常看到这个单词。原来是只Mozilla基金会,为支持和领导开源的Mozilla而设立的一个非营利组织。

cx_Freeze:打包工具,将python程序打包成exe文件。
下载地址: 点击打开链接
打包的稍后再研究。

cookie的内容通过cookiejar模块来操作,代码里面使用的是子类MozillaCookieJar。
cookie详细讲解看这里 点击打开链接
这个类跟父类只是保存和加载文件的方式有所不同。
看一下保存的内容,用\t分割。为方便查看,用""包着了。
cookie.domain:"s.m.taobao.com",访问的域名
initial_dot:"False",域名是否以“.”开始的,要做一些特殊处理。
cookie.path:"/" 好像是文件目录
secure:"False" 安全的
expires:"" 应该是过期时间
name:"JSESSIONID"
value:"770326E8F4997185C7DB2714D7569FF1"

request:
这不是新的模块,但是趁着这次详细了解了一番。

点击打开链接

下面说说具体的代码

1.这里去的是手机淘宝的页面,获得的信息居然是json来的。

2.代码的核心就是从网上下载网页。因为淘宝可能会出现反爬虫,所以使用cookie,构建head是很有必要的。尽量把自己伪装成一个浏览器。

3.把内容写到excel中。怎么写不重要了。反正没什么好看的。一个练习的例子,往往都是下载数据而已。

但是从数据到信息还差一步,这是一个商业秘密了。所以数据获得再多,不能转化为信息,最终还只是练习而已。

好吧,还是看看代码吧。

# -*- coding:utf-8 -*-
import urllib.request, urllib.parse, http.cookiejar
import os, time,re
from PIL import Image
import json
from openpyxl import Workbook# 找出文件夹下所有html后缀的文件
def listfiles(rootdir, prefix='.xml'):file = []for parent, _, filenames in os.walk(rootdir):if parent == rootdir:for filename in filenames:if filename.endswith(prefix):file.append(rootdir + '/' + filename)return fileelse:passdef writeexcel(path,dealcontent):workbook = Workbook() #构造一个workBook的对象 worksheet = workbook.create_sheet('1',0)#构造一个表格。坐标要从1开始的。for i in range(0,len(dealcontent)):for j in range(0,len(dealcontent[i])):if i!=0 and j==len(dealcontent[i])-1:if dealcontent[i][j] != '': try:worksheet.cell(row=i+1,column=j+1).value = dealcontent[i][j]#写入sheet中 except:passelse:if dealcontent[i][j]:worksheet.cell(row=i+1,column=j+1).value = dealcontent[i][j].replace(' ','') workbook.save(path)#这里才是代码的核心
def getHtml(url, myProxy='', postdata={}):"""抓取网页:支持cookieurl网址,postdata为POST的数据"""# COOKIE文件保存路径filename = 'cookie.txt'# 声明一个MozillaCookieJar对象实例保存在文件中cj = http.cookiejar.MozillaCookieJar(filename) # 从文件中读取cookie内容到变量# ignore_discard的意思是即使cookies将被丢弃也将它保存下来# ignore_expires的意思是如果过期了也照样保存# 如果存在,则读取主要COOKIEif os.path.exists(filename):cj.load(filename, ignore_discard=True, ignore_expires=True)# 建造带有COOKIE的处理器cookieHandler = urllib.request.HTTPCookieProcessor(cj)if myProxy:# 开启代理支持#使用代理,就要用到代理的HandlerproxyHandler = urllib.request.ProxyHandler({'http':'http://'+myProxy})print('代理:'+myProxy+'启动')opener = urllib.request.build_opener(proxyHandler, cookieHandler )else:opener = urllib.request.build_opener(cookieHandler)# 打开专家加头部opener.addheaders = [('User-Agent','Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5'),('Referer','http://s.m.taobao.com'),('Host', 'h5.m.taobao.com')]# 分配专家urllib.request.install_opener(opener)# 有数据需要POSTif postdata:# 数据URL编码postdata = urllib.parse.urlencode(postdata)html_bytes = urllib.request.urlopen(url, postdata.encode()).read()else:html_bytes = urllib.request.urlopen(url).read()# 保存COOKIE到文件中cj.save(ignore_discard=True, ignore_expires=True)return html_bytes# 去除标题中的非法字符 (Windows)
def validateTitle(title):rstr = r"[\/\\\:\*\?\"\<\>\|]"  # '/\:*?"<>|'new_title = re.sub(rstr, "", title)return new_title# 递归创建文件夹
def makeFolder(path):try:os.makedirs(path)except:print('目录已经存在:'+path)if __name__ == '__main__':#对应目录dataDir = './data' imageDir = './image'makeFolder(dataDir)#表单参数  keyword = r'卡包'orderType = 1 #1.按销量优先,2.按价格低到高,3.价格高到低,4.信用排序,5.综合排序pageNum = 10 #需要抓取的页数waitSeconds = 4#每次抓取后暂停时间isGetImage = 1#'抓取图片按1,不抓取按2:'#构建表单    postdata = {}postdata['event_submit_do_new_search_auction']= 1postdata['search']= '提交查询'postdata['_input_charset']= 'utf-8'postdata['topSearch']= 1postdata['atype']= 'b'postdata['searchfrom']= 1postdata['action']= 'home:redirect_app_action'postdata['from']= 1postdata['q']= keywordpostdata['sst']= 1postdata['n']= 20postdata['buying']= 'buyitnow'postdata['m']= 'api4h5'postdata['abtest']= 16postdata['wlsort']= 16postdata['style']= 'list'postdata['closeModues']= 'nav,selecthot,onesearch'if orderType == 1:postdata['sort'] = '_sale'elif orderType == 2:postdata['sort'] = 'bid'elif orderType== 2:postdata['sort']='_bid'elif orderType==4:postdata['sort']='_ratesum'#获取每一页的数据for page in range(0, pageNum): postdata['page']= page taobaoUrl = "http://s.m.taobao.com/search?" try:content1 = getHtml(taobaoUrl, '', postdata)file = open(dataDir + '/' + str(page) + '.json', 'wb')#这是手机淘宝,获得的是json文件file.write(content1)except Exception as e:if hasattr(e, 'code'):print('页面不存在或时间太长.')print('Error code:', e.code)elif hasattr(e, 'reason'):print("无法到达主机.")print('Reason:  ', e.reason)else:print(e)time.sleep(waitSeconds)print('暂停'+str(waitSeconds)+'秒')    files = listfiles(dataDir, '.json')total = [['页数', '店名', '商品标题', '商品打折价', '发货地址', '评论数', '原价', '售出件数', '政策享受', '付款人数', '金币折扣','URL地址','图像URL','图像'],]for filename in files:try:doc = open(filename, 'rb')doccontent = doc.read().decode('utf-8', 'ignore')product = doccontent.replace(' ', '').replace('\n', '')product = json.loads(product)onefile = product['listItem']except:print('抓不到' + filename)continuefor item in onefile:itemlist = [filename, item['nick'], item['title'], item['price'], item['location'], item['commentCount']]itemlist.append(item['originalPrice']) itemlist.append(item['sold'])itemlist.append(item['zkType'])itemlist.append(item['act'])itemlist.append(item['coinLimit'])itemlist.append('http:'+item['url'])picpath=item['pic_path'].replace('60x60','720x720')itemlist.append(picpath)if isGetImage==1:if os.path.exists(imageDir):passelse:makeFolder(imageDir)url=urllib.parse.quote(picpath).replace('%3A',':')urllib.request.urlcleanup()try:pic=urllib.request.urlopen(url)picno=time.strftime('%H%M%S', time.localtime())filenamep=imageDir+'/'+picno+validateTitle(item['nick']+'-'+item['title'])filenamepp=filenamep+'.jpeg'sfilename=filenamep+'s.jpeg'filess=open(filenamepp,'wb')#从网络上获得图片filess.write(pic.read())filess.close()img = Image.open(filenamepp)#以图片的格式打开w, h = img.sizesize=w/6,h/6img.thumbnail(size, Image.ANTIALIAS)img.save(sfilename,'jpeg')itemlist.append(sfilename)print('抓到图片:'+sfilename)except Exception as e:if hasattr(e, 'code'):print('页面不存在或时间太长.')print('Error code:', e.code)elif hasattr(e, 'reason'):print("无法到达主机.")print('Reason:  ', e.reason)else:print(e)itemlist.append('')else:itemlist.append('') total.append(itemlist)if len(total) > 1:  writeexcel( keyword + '淘宝手机商品.xlsx', total)else:print('什么都抓不到')

Python3实例:爬取淘宝商品列表相关推荐

  1. Python + selenium 爬取淘宝商品列表及商品评论 2021-08-26

    Python + selenium 爬取淘宝商品列表及商品评论[2021-08-26] 主要内容 登录淘宝 获取商品列表 获取评论信息 存入数据库 需要提醒 主要内容 通过python3.8+ sel ...

  2. 使用Selenium爬取淘宝商品(绕过登录页面)

    文章目录 1.准备工作 2.接口分析 3.页面分析 4.获取商品列表 5.解析商品列表 6.保存到MongoDB 7.遍历每页 8.异常处理(绕过登录反爬机制) 方法一:修改ChromeDriver. ...

  3. python+scrapy简单爬取淘宝商品信息

    python结合scrapy爬取淘宝商品信息 一.功能说明: 已实现功能: 通过scrapy接入selenium获取淘宝关键字搜索内容下的商品信息. 待扩展功能: 爬取商品中的全部其他商品信息. 二. ...

  4. python爬取淘宝商品做数据挖掘

    作业要求:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/3159 项目内容: 本项目选择 淘宝商品类目:零食 数量:一共100页,44 ...

  5. python淘宝爬虫_python爬虫爬取淘宝商品信息

    本文实例为大家分享了python爬取淘宝商品的具体代码,供大家参考,具体内容如下 import requests as req import re def getHTMLText(url): try: ...

  6. 利用Selenium爬取淘宝商品信息

    文章来源:公众号-智能化IT系统. 一.  Selenium和PhantomJS介绍 Selenium是一个用于Web应用程序测试的工具,Selenium直接运行在浏览器中,就像真正的用户在操作一样. ...

  7. 爬取淘宝商品信息selenium+pyquery+mongodb

    ''' 爬取淘宝商品信息,通过selenium获得渲染后的源码,pyquery解析,mongodb存储 '''from selenium import webdriver from selenium. ...

  8. python爬淘宝商品销量信息_python爬取淘宝商品销量信息

    python爬取淘宝商品销量的程序,运行程序,输入想要爬取的商品关键词,在代码中的'###'可以进一步约束商品的属性,比如某某作者的书籍,可以在###处输入作者名字,以及时期等等.最后可以得到所要商品 ...

  9. 2021-11-16爬取淘宝商品信息时如何获取cookie

    爬取淘宝商品信息时如何获取cookie ###一.基本环境 1.win10系统 2.火狐浏览器 3.编程软件anaconda 4.淘宝的robots:https://www.taobao.com/ro ...

最新文章

  1. 图像处理中消除相机透镜畸变和视角变换
  2. dojo中的dojo/dom-class
  3. shell学习笔记二则:统计空间
  4. 用python编写密码安全性_密码安全性
  5. nginx自签ssl证书
  6. [NOIp2017 DG Day 2 T1] 奶酪
  7. 论文查重算法 python_论文查重降重绝密方法
  8. Matlab颜色对照(RGB三元组、十六进制表示)
  9. EditPlus使用编辑Object C
  10. OneData指标体系
  11. web前端开发面试题-基础篇
  12. matlab中三维数组,维数转换
  13. C++【C++11】
  14. 经纬度换算数值_如何在Excel中将经纬度数值转换成度分秒
  15. bzoj 1022: [SHOI2008]小约翰的游戏John anti_nim游戏
  16. 计算机视觉工具、代码合集
  17. 如来问:“你们带U盘了么”
  18. 中药复方组方网络药理学tcmsp中药数据库全部中药502个,化合物共14249个 网络药理学数据
  19. 关于国内Android游戏的真相
  20. float型浮点数的精确位数

热门文章

  1. error: conflicting types for xxx in c
  2. 用Java重命名MP3歌曲文件
  3. 查看linux的系统信息
  4. Linux学习之路——常见指令详细总结(中)
  5. linux内核的文件组织形式
  6. php 系统平均负载,深入理解liunx平均负载
  7. 达人评测 华硕ROG 幻 14 2022款怎么样
  8. python多维数组拟合_python归一化多维数组的方法
  9. 网络规划与设计实验+配置案例报告+pkt
  10. RC4加密算法C++实现