爬虫案例——淘宝图片爬虫

在淘宝网中搜索某种商品之后会跳转到新的网页,网页的底部有可以进行换页,爬虫之前我们需要找出不同页码之间是否存在某种规律。

https://s.taobao.com/search?q=%E7%9F%AD%E8%A3%99&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.2017.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306

https://s.taobao.com/search?q=%E7%9F%AD%E8%A3%99&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.2017.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306&bcoffset=4&ntoffset=4&p4ppushleft=1%2C48&s=44

https://s.taobao.com/search?q=%E7%9F%AD%E8%A3%99&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.2017.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306&bcoffset=4&ntoffset=4&p4ppushleft=1%2C48&s=88

可以发现,第一页的url中是没有s=?的,从第二页开始s=44,第三页s=88,找到规律之后可以通过循环进行跨页爬取了

import urllib.request
import re
keyname='短裙'
keyname=urllib.request.quote(keyname)
headers=('User-Agent',"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36")
opener=urllib.request.build_opener()
opener.addheaders=[headers]
urllib.request.install_opener(opener)
for i in range(0,2):
    url='https://s.taobao.com/search?q='+keyname+'&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.2017.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306&bcoffset=4&ntoffset=4&p4ppushleft=1%2C48&s='+str(i*44)
    data=urllib.request.urlopen(url).read().decode('utf-8','ignore')
    pat='pic_url":"//(.*?)"'
    imagelist=re.compile(pat).findall(data)
    for j in range(0,len(imagelist)):
        thisimage=imagelist[j]
        thisurl='http://'+thisimage
        file='D:/1python/淘宝/'+str(i)+str(j)+'.jpg'
        urllib.request.urlretrieve(thisurl,file)

你可能感兴趣的:(Python小tips)