python 爬虫一键爬取 淘宝天猫宝贝页面主图颜色图和详情图的教程


Posted in Python onMay 22, 2018

实例如下所示:

import requests
import re,sys,os
import json
import threading
import pprint
class spider:
 def __init__(self,sid,name):
 
 self.id = sid
 self.headers = { "Accept":"text/html,application/xhtml+xml,application/xml;",
  "Accept-Encoding":"gzip",
  "Accept-Language":"zh-CN,zh;q=0.8",
  "Referer":"http://www.example.com/",
  "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
  }
 
 self.name=name
 def openurl(self,url):
 
 self.request = requests.get(url,headers = self.headers) 
 if self.request.ok:
  return self.request.text
  
 def matchs(self):
 
 tmall_exp = r"Setup\(([\s\S]+?)\);"### 匹配商品数据的正则
 detail= r"src=\"(https://img\S+?[jpgifn]+?)\"" ###匹配 商品详情图的正则
 html = self.openurl("https://detail.tmall.com/item.htm?id=%s"%self.id)
 data = re.findall(tmall_exp,html)
 data = json.loads(data[0])
 main_img = data['propertyPics'] ## 这里包括了主图和颜色图的地址
 color_data =data['valItemInfo'] ['skuList'] ### 这里获得商品的颜色信息列表 包括颜色编码 颜色名称,商品skuID
 detail_html = self.openurl("http:"+data['api']["httpsDescUrl"])
 detail_image = re.findall(detail,detail_html)
 self.newdata={"MAIN":main_img['default'],"DETAIL":detail_image,"id":self.id,}
 
 psvs = []
 self.newdata['COLOR']=[]
 
 for v in range(len(color_data)):
  if ";"in color_data[v]["pvs"]:
  psv = color_data[v]['pvs'][color_data[v]['pvs'].find(";")+1:]
  else:
  psv = color_data[v]['pvs']
  if psv in psvs:
  
  continue
  psvs.append(psv)
 
  self.newdata['COLOR'].append({color_data[v]["names"]:main_img[";"+psv+";"]})
  
 pprint.pprint(self.newdata)
 
 return self.newdata
 
 def download(self):
 if len(self.newdata)>0:
  for x in range(len(self.newdata['MAIN'])):
  
  threading.Thread(target=self.download_main,args=(self.newdata['MAIN'][x],x)).start()
  
  for x in self.newdata['COLOR']:
  
  threading.Thread(target=self.download_color,args=(x,)).start()
  for x in range(len(self.newdata['DETAIL'])):
  
  threading.Thread(target=self.download_detail,args=(self.newdata['DETAIL'][x],x)).start()
 return
 def download_main(self,url,index):
 try:
  img = requests.get("http:"+url,stream=True,headers = self.headers,timeout=10)
 except:
  print(sys.exc_info())
  return
 if img.ok:
  if not os.path.exists(self.name+"/main"):
  try:
   os.makedirs(self.name+"/main")
  except:
   pass
  imgs = open(self.name+"/main/%s.jpg"%index,"wb")
  imgs.write(img.content)
  imgs.close()
  
 def download_color(self,url):
  
 try:
  img = requests.get("http:"+url[list(url.keys())[0]][0],stream=True,headers = self.headers,timeout=10)
 except:
  print(sys.exc_info())
  return
 if img.ok:
  if not os.path.exists(self.name+"/color"):
  try:
   os.makedirs(self.name+"/color")
  except:
   pass
  if "/"in list(url.keys())[0]:
  color = list(url.keys())[0].replace("/","_")
  elif "\\" in list(url.keys())[0]:
  color = list(url.keys())[0].replace("\\","_")
  else:
  color = list(url.keys())[0]
  imgs = open(self.name+"/color/%s.jpg"%color,"wb")
  imgs.write(img.content)
  imgs.close()
 def download_detail(self,url,index):
 try:
  img = requests.get(url,stream=True,headers = self.headers,timeout=10)
 except:
  print(sys.exc_info())
  return
 if img.ok:
  if not os.path.exists(self.name+"/detail"):
  try:
   os.makedirs(self.name+"/detail")
  except:
   pass
  
  imgs = open(self.name+"/detail/%s.jpg"%index,"wb")
  imgs.write(img.content)
  imgs.close()
  
if __name__ =="__main__":
 
 sid = 528766269341 ## 这里输入天猫宝贝ID
 taobao = spider(sid,"下载图片/T")
 taobao.matchs()
 taobao.download()

以上这篇python 爬虫一键爬取 淘宝天猫宝贝页面主图颜色图和详情图的教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python 参数列表中的self 显式不等于冗余
Dec 01 Python
Python实现把xml或xsl转换为html格式
Apr 08 Python
python中lambda与def用法对比实例分析
Apr 30 Python
Python程序中用csv模块来操作csv文件的基本使用教程
Mar 03 Python
PyCharm使用教程之搭建Python开发环境
Jun 07 Python
Python定时器实例代码
Nov 01 Python
Python编程实现从字典中提取子集的方法分析
Feb 09 Python
使用Python抓取豆瓣影评数据的方法
Oct 17 Python
利用Python如何实现一个小说网站雏形
Nov 23 Python
Pycharm之快速定位到某行快捷键的方法
Jan 20 Python
Pytest mark使用实例及原理解析
Feb 22 Python
python给list排序的简单方法
Dec 10 Python
python3.x实现发送邮件功能
May 22 #Python
python 爬虫 批量获取代理ip的实例代码
May 22 #Python
python 获取当天每个准点时间戳的实例
May 22 #Python
selenium+python 去除启动的黑色cmd窗口方法
May 22 #Python
python3实现163邮箱SMTP发送邮件
May 22 #Python
django请求返回不同的类型图片json,xml,html的实例
May 22 #Python
Django使用HttpResponse返回图片并显示的方法
May 22 #Python
You might like
php与mysql建立连接并执行SQL语句的代码
2011/07/04 PHP
使用PHP获取汉字的拼音(全部与首字母)
2013/06/27 PHP
php实现文件下载实例分享
2014/06/02 PHP
php发送短信验证码完成注册功能
2015/11/24 PHP
php判断某个方法是否存在函数function_exists (),method_exists()与is_callable()区别与用法解析
2020/04/20 PHP
浅析jQuery的链式调用之each函数
2010/12/03 Javascript
基于jQuery的message插件实现右下角弹出消息框
2011/01/11 Javascript
js 判断上传文件大小及格式代码
2013/11/13 Javascript
遍历DOM对象内的元素属性示例代码
2014/02/08 Javascript
js类型转换与引用类型详解(Boolean_Number_String)
2014/03/07 Javascript
JavaScript判断undefined类型的正确方法
2015/06/30 Javascript
JS仿淘宝实现的简单滑动门效果代码
2015/10/14 Javascript
JavaScript和HTML DOM的区别与联系及Javascript和DOM的关系
2015/11/15 Javascript
js格式化时间的方法
2015/12/18 Javascript
Vue.js每天必学之数据双向绑定
2016/09/05 Javascript
bootstrap滚动监控器使用方法解析
2017/01/13 Javascript
安装vue-cli报错 -4058 的解决方法
2017/10/19 Javascript
vue回到顶部监听滚动事件详解
2019/08/02 Javascript
python中list列表的高级函数
2016/05/17 Python
Python File readlines() 使用方法
2018/03/19 Python
win8.1安装Python 2.7版环境图文详解
2019/07/01 Python
Python文本处理简单易懂方法解析
2019/12/19 Python
python 工具 字符串转numpy浮点数组的实现
2020/03/14 Python
PyCharm配置anaconda环境的步骤详解
2020/07/31 Python
详解pycharm自动import所需的库的操作方法
2020/11/30 Python
使用 css3 transform 属性来变换背景图的方法
2019/05/07 HTML / CSS
全球异乡人的跨境社交电商平台:Kouhigh口嗨网
2020/07/24 全球购物
大学四年规划书范文
2013/12/27 职场文书
四年级下册教学反思
2014/02/01 职场文书
《自选商场》教学反思
2014/02/14 职场文书
入党团支部推荐意见
2015/06/02 职场文书
预备党员入党感想
2015/08/10 职场文书
演讲稿:态度决定一切
2019/04/02 职场文书
position:sticky 粘性定位的几种巧妙应用详解
2021/04/24 HTML / CSS
SpringBoot整合阿里云视频点播的过程详解
2021/12/06 Java/Android
Win10服务全部禁用了怎么启动?Win10服务全部禁用解决方法
2022/09/23 数码科技