图片爬虫

爬取图片的思路与过程
(1)建立一个爬取图片的自定义函数,该函数负责爬取一个页面下的我们想爬取的图片,爬取过程为:首先通过urllib
.request.urlopen(url).read()读取对应网页的全部代码,然后根据第一个正则表达式进行第一次信息过滤,过滤完
成后,在第一次过滤结果的基础上,根据第二个正则表达式进行第二次信息过滤,提取出该网页上所有目标图片的链接,并
将这些链接地址存储在一个列表中,随后遍历该列表,分别将对应链接通过urllib.request.urlretrieve(imageurl,
filename=imagename)存储到本地,为了避免程序中途异常崩溃,我们可以建立异常处理,若不能爬取某个图片,则通过
X+=1自动跳到下一个图片。
(2)通过for循环将该分类下的所有网页都爬取一遍。

import re
import urllib.request
httphd=urllib.request.HTTPHandler(debuglevel=1)
httpshd=urllib.request.HTTPSHandler(debuglevel=1)
opener=urllib.request.build_opener(httphd,httpshd)
urllib.request.install_opener(opener)

def craw(url,page):
    html1=urllib.request.urlopen(url).read()
    html1=str(html1)
    pat1='<div id="plist".+? <div class="page clearfix">'
    result1=re.compile(pat1).findall(html1)
    result1=result1[0]

    with open("E:/我的作业/myimage/1.txt","wb") as fhandle:
        fhandle.write(str.encode(result1))
        fhandle.close()

    pat2='<img width="220" height="220" data-img="1" src="//(.+?[\.jpg|\.png])"'
    imagelist=re.compile(pat2).findall(result1)

    with open("E:/我的作业/myimage/2.txt","ab") as f:
        for i in range(0,len(imagelist)):
            f.write(str.encode(imagelist[i]))
            f.write(str.encode("\n"))
        f.close()

    x=1
    for imageurl in imagelist:
        imagename="E:/我的作业/myimage/"+str(page)+"页第"+str(x)+".jpg"
        imageurl="http://"+imageurl
        try:
            urllib.request.urlretrieve(imageurl,filename=imagename)
            print("保存成功!!!")
        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,10):
    url="https://list.jd.com/list.html?cat=9987,653,655&page="+str(i)
    craw(url,i)

猜你喜欢

转载自blog.csdn.net/SteveForever/article/details/81193302