python爬虫数据-下载图片经典案例



'''
Urllib 模块提供了读取web页面数据的接口,我们可以像读取本地文件一样读取wwwftp上的数据。首先,我们定义了一个getHtml()函数:

  urllib.urlopen()方法用于打开一个URL地址。

  read()方法用于读取URL上的数据,向getHtml()函数传递一个网址,并把整个页面下载下来。执行程序就会把整个网页打印输出。
'''


# 筛选页面中想要的数据

import re
import urllib.request
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
html = html.decode('utf-8')
#TypeError: cannot use a string pattern on a bytes-like object
return html

# 我们又创建了getImg()函数,用于在获取的整个页面中筛选需要的图片连接。re模块主要包含了正则表达式:
#
#   re.compile() 可以把正则表达式编译成一个正则表达式对象.
#
#   re.findall() 方法读取html 中包含 imgre(正则表达式)的数据。
#
#    运行脚本将得到整个页面中包含图片的URL地址。
def getImg(html):
reg = r'src="(.+?.jpg)" pic_ext'
imgre = re.compile(reg)
imglist = re.findall(imgre,html)
return imglist

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

# 把图片地址通过for循环遍历并保存在本地,如下所示:
List = getImg(html)
x=0
for imgurl in List:
urllib.request.urlretrieve(imgurl,'D:img\%s.jpg' % x)
x+=1
# print(x)





原文地址:https://www.cnblogs.com/sincoolvip/p/7274375.html