爬取淘宝商品图片(用户代理池)

import urllib.request
import re
keyname="西裤"
key=urllib.request.quote(keyname)
import random
uapools=[
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360SE",
    "Opera/12.02 (Android 4.1; Linux; Opera Mobi/ADR-1111101157; U; en-US) Presto/2.9.201 Version/12.02",
    ]

def ua(uapools):
    thisua=random.choice(uapools)
    print(thisua)
    headers=("User-Agent",thisua)
    opener=urllib.request.build_opener()
    opener.addheaders=[headers]
    urllib.request.install_opener(opener)

for i in range(1,101):
    url="https://s.taobao.com/search?q=" + key + "&s=" + str((i-1)*44)
    ua(uapools)
    data=urllib.request.urlopen(url).read().decode("utf-8", "ignore")
    pat='"pic_url":"//(.*?)"'
    imglist=re.compile(pat).findall(data)
    for j in range(0,len(imglist)):
        try:
            thisimg=imglist[j]
            thisimgurl="http://"+thisimg
            localfile="D:/tmp/a/" + str(i) + str(j) + ".jpg"
            urllib.request.urlretrieve(thisimgurl, filename=localfile)
        except Exception as err:
            print(err)

你可能感兴趣的:(爬取淘宝商品图片(用户代理池))