zoukankan      html  css  js  c++  java
  • python+requests抓取页面图片

    前言:     

    学完requests库后,想到可以利用python+requests爬取页面图片,想到实战一下。依照现在所学只能爬取图片在html页面的而不能爬取由JavaScript生成的图片,所以我选取饿了打开下面这个页面http://p.weather.com.cn/2017/06/2720826.shtml#p=7

    案例步骤:

    1.利用requests库,调用requests库中的get()方法,打开需要爬去的页面url,返回页面内容,下面是自定义的打开页面的方法

    def load_page(url):
        response=requests.get(url)
        data=response.content
        return data
    

    2.用正则表达式去匹配页面的图片链接,匹配成功后,把图片下载下来,保存到对应的文件位置,下面是自定义的保存图片方法

    def get_image(html):
        regx=r'http://[S]*jpg'
        pattern=re.compile(regx)
        get_images=re.findall(pattern,repr(html))
    
        num=1
        for img in  get_images:
            image=load_page(img)
            with open('./spider_picture/%s.jpg' % num,'wb') as fb:
                fb.write(image)
                print("正在下载第%s张图片" %num)
                num=num+1
        print("下载完成!")
    

      完整案例源码:

    # coding:utf-8
    # 引入requests包和正则表达式包re
    import requests
    import re
    
    # 自定义下载页面函数
    def load_page(url):
        response=requests.get(url)
        data=response.content
        return data
    
    # 自定义保存页面图片函数
    def get_image(html):
        regx=r'http://[S]*jpg'  # 定义图片正则表达式
        pattern=re.compile(regx) # 编译表达式构造匹配模式
        get_images=re.findall(pattern,repr(html)) # 在页面中匹配图片链接
    
        num=1
        # 遍历匹配成功的链接
        for img in  get_images:
            image=load_page(img) #根据图片链接,下载图片链接
            # 将下载的图片保存到对应的文件夹中
            with open('./spider_picture/%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=7'
    # 调用load_page函数,下载页面内容
    html = load_page(url)
    # 在页面中,匹配图片链接,并将图片下载下来,保存到对应文件夹
    get_image(html)            

      

  • 相关阅读:
    Ruby笔记四(数组)
    中央直属企业名单【中国级别最高的169家企业】(转)找工作按这个来
    循环pthread_create导致虚拟内存上涨(续1)
    除掉行数小程序
    client comserver编译配置运行详细说明
    网络监听技术概览(转待看)
    查看 linux系统版本,内核,CPU,MEM,位数的相关命令(实验)
    项目中Shell脚本说明(待完善)
    多线程 or 多进程 (实验1)
    循环pthread_create导致虚拟内存上涨(续2)
  • 原文地址:https://www.cnblogs.com/101718qiong/p/8192199.html
Copyright © 2011-2022 走看看