完整代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import os import re import urllib import urllib.request
def get_html(url): page = urllib.request.urlopen(url) html_a = page.read() return html_a.decode('utf-8')
def get_img(url): x = 1 # 声明一个变量赋值 html_b = get_html(url) reg = r'https://[^\s]*?\.jpg' imgre = re.compile(reg) # 转换成一个正则对象 imglist = imgre.findall(html_b) # 表示在整个网页过滤出所有图片的地址,放在imgList中 path = os.getcwd() + os.sep + 'image' # 设置图片的保存地址 if not os.path.isdir(path): os.makedirs(path) # 判断没有此路径则创建 paths = path + '\\' # 保存在test路径下 for imgurl in imglist: urllib.request.urlretrieve(imgurl, '{0}{1}.jpg'.format(paths, x)) # 打开imgList,下载图片到本地 print('开始下载第%s张图片'%x) x = x + 1
url = input("请输入网址") #url = get_img(url)
|