python下载图片实现方法(超简单)


当前第2页 返回上一页

三、图片下载


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#coding=utf-8

  import urllib

  import re

  def getHtml(url):

    page = urllib.urlopen(url)

    html = page.read()

    return html

  def getImg(html):

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

    imgre = re.compile(reg)

    imglist = re.findall(imgre,html)

    x = 0

    for imgurl in imglist:

      urllib.urlretrieve(imgurl,'%s.jpg' % x)

      x+=1

  html = getHtml("https://tieba.baidu.com/p/5582243679")

  print getImg(html)


通过for循环获得所有符合条件的图片网址,并采用urllib.urlretrieve()方法,将远程数据下载到本地,并重新命名!

以下是补充

如下所示:


1

2

3

4

5

6

import urllib.request

response = urllib.request.urlopen('http://www.jb51.net/g/500/600')

cat_img = response.read()

 

with open('cat_500_600.jpg','wb') as f:

 f.write(cat_img)


urlopen()括号里既可以是一个字符串也可以是一个request对象,当传入字符串的时候会转换成一个request对象,因此代码

response = urllib.request.urlopen('http://www.jb51.net/g/500/600') 也可以写成

req = urllib.request.Request('http://www.jb51.net/g/500/600')

1、response = urllib.request.urlopen(req)
2、responce还有geturl,info,getcode方法


代码with open('cat_500_600.jpg','wb') as f:

f.write(cat_img)等价于

1、f = open('cat_500_600.jpg','wb')

2、try:

3、 data = f.write(cat_img)

4、finally:

5、 f.close()

相关推荐:

Python简单计算文件MD5值的方法示例

Python简单实现控制电脑的方法


以上就是python下载图片实现方法(超简单)的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python怎么发音

Python如何打印出菱形与三角形以及矩形的代码示例分享

Python可变类型和不可变类型区别

Python怎么查看变量类型

Python中数据结构与算法的应用(附示例)

Python是什么,如何使用Python

Python中什么是语句块?

Python:中input()与raw_input()的详解

Python中for循环与range()函数的简单介绍(附示例)

Python要用什么软件

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...