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

yipeiwu_com5年前Python爬虫

实例如下所示:

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设计】。

相关文章

在scrapy中使用phantomJS实现异步爬取的方法

使用selenium能够非常方便的获取网页的ajax内容,并且能够模拟用户点击和输入文本等诸多操作,这在使用scrapy爬取网页的过程中非常有用。 网上将selenium集成到scrap...

Python爬虫之pandas基本安装与使用方法示例

本文实例讲述了Python爬虫之pandas基本安装与使用方法。分享给大家供大家参考,具体如下: 一、简介: Python Data Analysis Library 或 pandas...

python爬虫 正则表达式使用技巧及爬取个人博客的实例讲解

python爬虫 正则表达式使用技巧及爬取个人博客的实例讲解

这篇博客是自己《数据挖掘与分析》课程讲到正则表达式爬虫的相关内容,主要简单介绍Python正则表达式爬虫,同时讲述常见的正则表达式分析方法,最后通过实例爬取作者的个人博客网站。希望这篇基...

python爬虫selenium和phantomJs使用方法解析

python爬虫selenium和phantomJs使用方法解析

1.selenum:三方库。可以实现让浏览器完成自动化的操作。 2.环境搭建 2.1 安装: pip install selenium 2.2 获取浏览器的驱动程序 下载地址...

python爬取淘宝商品销量信息

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