python3 爬取图片的实例代码

yipeiwu_com6年前Python爬虫

具体代码如下所示:

#coding=utf8
from urllib import request
import re
import urllib,os
url='http://tieba.baidu.com/p/3840085725'
def get_image(url):
  #获取页面源码
  page = urllib.request.urlopen(url)
  html = page.read()
  #解码,否则报错
  html = html.decode('utf8')
  #正则匹配获取()的内容
  reg = r'src="(https.+?.[jpg,png])"'
  imge = re.compile(reg)
  # 获取正则匹配的数据,"(.+?.jpg)" 的数据,返回一个list
  imglist = imge.findall(html)
  return imglist
def save_img(imglist):
  dir = os.path.join(os.path.dirname(__file__),'img')
  i=1
  for img in imglist:
    #python3格式化字符串的另一种写法
    imgpath = f'{dir}\\image{i}.jpg'
    try:
      #urlretrieve下载图片并保存到本地
      urllib.request.urlretrieve(img,imgpath)
      i += 1
      print(u'图片开始下载')
    except Exception:
      print(f'image:{img}下载失败')
      continue
imglist = get_image(url)
save_img(imglist)

总结

以上所述是小编给大家介绍的python3 爬取图片的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

以视频爬取实例讲解Python爬虫神器Beautiful Soup用法

1.安装BeautifulSoup4 easy_install安装方式,easy_install需要提前安装 easy_install beautifulsoup4 pip安装方...

python scrapy爬虫代码及填坑

python scrapy爬虫代码及填坑

涉及到详情页爬取 目录结构: kaoshi_bqg.py import scrapy from scrapy.spiders import Rule from scrapy.lin...

Python爬虫通过替换http request header来欺骗浏览器实现登录功能

Python爬虫通过替换http request header来欺骗浏览器实现登录功能

以豆瓣为例,访问https://www.douban.com/contacts/list 来查看自己关注的人,要登录才能查看。 如果用requests.get()方法获取这个http,没...

Python3.x爬虫下载网页图片的实例讲解

Python3.x爬虫下载网页图片的实例讲解

一、选取网址进行爬虫 本次我们选取pixabay图片网站 url=https://pixabay.com/ 二、选择图片右键选择查看元素来寻找图片链接的规则 通过查看多个图...

python 每天如何定时启动爬虫任务(实现方法分享)

python2.7环境下运行 安装相关模块 想要每天定时启动,最好是把程序放在linux服务器上运行,毕竟linux可以不用关机,即定时任务一直存活; #coding:utf8 im...