python爬虫下载图片

python爬虫下载图片

    如何通过python爬虫下载图片。

实现效果:

《python爬虫下载图片》

实现思路:

1.确定下载图片的数据源url

2.获取html dom

3.通过正则表达式截取html dom,获取图片url列表

4.遍历url列表下载图片,并保存到本地磁盘

实现代码:

from datetime import time
from urllib import request
import re
import urllib
import uuid

import os

#爬取网址

url1='http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E6%96%B0%E5%B9%B4'


# 请求
Request = request.urlopen(url1)
print(request)
# 爬取链接获取html dom
Response =Request.read()
Response = Response.decode('utf-8')
print(Response)
# 正则表达式截取图片路径
urlList=re.findall(r'"objURL".{20,99}jpg',Response)
print('获取网址1',urlList)

i=0
for imgurl in urlList:

    i=int(i)
    #y=str(f)
    imgurl=imgurl.lstrip('"objURL":')
    print('获取链接',imgurl)
    Request=urllib.request.urlopen(imgurl)


    # 获取下载图片的返回IO
    Response = Request.read()
    print(Response)
    i+=1



    filename=str(uuid.uuid1())+'.jpg'

    print('保存路径',  filename)


    fileurl="d:/reptileImg/"

    #判断路径是否存在,不存在则创建路径
    if os.path.isdir(fileurl):
        print()
    else:
        os.mkdir(fileurl)

    file = open(fileurl+filename, 'wb')
    # # 打印结果
    file.write(Response)
    print('次数', i)

    file.close()



    原文作者:kerryqpw
    原文地址: https://blog.csdn.net/kerryqpw/article/details/79154395
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞