运行环境Python3.6.4
# 爬取京东手机图片
import re #导入re模块
import urllib.request #导入urllib.request模块
def craw(url,page): #定义函数craw
html1 = urllib.request.urlopen(url).read() #调用urllib.request模块里的urlopen函数打开url链接,并且读取,最后赋值给html1
html1 = str(html1) #将html1网页内容变成字符串
pat1 = '''<div id="plist".+? <div class="page clearfix">''' #利用pat1正则表达式进行第一次信息过滤
result1 = re.compile(pat1).findall(html1) #查找所有符合条件的信息
result1 = result1[0]
pat2 = '''<img width="220" height="220" data-img="1".+?"//(.+?\.jpg)">'''#".+?"组合可以匹配除换行外的任意字符,第二个正则表达式进行第二次过滤
imagelist = re.compile(pat2).findall(result1)
x = 1
for imageurl in imagelist:
imagename = "D:/Python35/myweb/part6/img1/"+"第"+str(page)+"页图"+str(x)+".jpg"
imageurl = "http://"+imageurl
try:
urllib.request.urlretrieve(imageurl,filename=imagename)
except urllib.error.URLError as e:
if hasattr(e,"code"):
x+=1
if hasattr(e,"reason"):
x+=1
x+=1
for i in range(1,2):
url = "http://list.jd.com/list.html?cat=9987,653,655&page="+str(i)
craw(url,i)