Python爬虫之下载网页图片

传统的方式是在想要的图片上鼠标点击右键另存为,或者用截图的方式保存图片,其实我们还可以通过使用简单的Python语言实现图片的下载并保存到本地,下面让我们看看如何实现吧

一、确定图片的URL地址及获取URL网页页面的信息

#coding:utf-8

fromurllib.requestimporturlopen    #导入urlopen

defgetHtml(url):

    page = urlopen(url)   

    html = page.read()    #读取URL

    returnhtml

html = getHtml("http://g.hiphotos.baidu.com/image/pic/item/8694a4c27d1ed21bd85def25a46eddc450da3f5e.jpg")    #访问URL地址

print(html)

二、通过正则表达筛选想要的页面数据

www.cnblogs.com/fnng/archive/2013/05/20/3089816.html

www.jianshu.com/p/6bc77094374a

通过审查页面元素,可以找到图片的地址,如下:src=”https://imgsa.baidu.com/forum/pic/item/f6738bd4b31c8701b540a1bf257f9e2f0608fff1.jpg”


img_24b8593f8334b907d685330fdcf96b79.png
摘自百度图片

修改后代码如下:

#coding:utf-8

fromurllib.requestimporturlopen

importre

defgetHtml(url):

    page = urlopen(url)

    html = page.read()

    returnhtml

defgetImg():

    reg =r'src="(.+?\.jpg)" pic_ext'    #通过正则表达获取图片数据

    img = re.compile(reg)     

    img_list = re.findall(img,html)

    returnimg_list

html = getHtml("http://g.hiphotos.baidu.com/image/pic/item/8694a4c27d1ed21bd85def25a46eddc450da3f5e.jpg")

print(html)

三、将获取的数据保存到本地

通过for循环遍历并下载到本地,代码如下:

#coding:utf-8

fromurllib.requestimporturlopen

importre

importurllib

defgetHtml(url):

    page = urlopen(url)

    html = page.read()

    returnhtml

defgetImg():

    reg =r'src="(.+?\.jpg)" pic_ext'

    img = re.compile(reg)

    img_list = re.findall(img,html)

    x =0

    forimgurlinimg_list:

        urllib.urlretrieve(imgurl,'%s.jpg'% x)   #urllib.urlretrieve()方法,下载并保留到本地

        x +=1

html = getHtml("http://g.hiphotos.baidu.com/image/pic/item/8694a4c27d1ed21bd85def25a46eddc450da3f5e.jpg")

print(html)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值