Python 爬虫 ——爬取Web页面图片

从网页页面上批量下载jpg格式图片,并按照数字递增命名保存到指定的文件夹。
Web地址:http://p.weather.com.cn/2017/06/2720826.shtml#p=1

import urllib   #请求Http
import urllib.request
import re   #正则匹配的库

#解析页面
def load_page(url) : #打开网页
    request=urllib.request.Request(url) #根据链接请求打开页面
    response=urllib.request.urlopen(request)
    data=response.read()    #获取页面响应数据
    return data

def get_image(html):
    regx=r'http://[\S]*jpg' #定义正则表达式,匹配页面图片元素
    pattern=re.compile(regx)    #编译表达式构造匹配模式
    get_image=re.findall(pattern,repr(html))    #进行正则表达式并返回结果

    num=1
    #遍历获取图片
    for img in get_image:
        image=load_page(img)
        #将图片存入到指定文件夹
        with open('E:\\Photo\\%s.jpg' %num,'wb') as fb:
            fb.write(image)
            print("正在下载第%s张图片" %num)
            num=num+1
    print("下载完成!")

url='http://p.weather.com.cn/2017/06/2720826.shtml#p=1'
html=load_page(url)
get_image(html)

在这里插入图片描述

去E:\Photo查看
在这里插入图片描述

正则表达式相关知识:正则表达式30分钟入门教程

猜你喜欢

转载自blog.csdn.net/weixin_43264177/article/details/82924604