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)            

      

  • 相关阅读:
    后台写js 并跳转
    visual studio 2010 js 调试
    网页搜索功能 多表搜索sql
    c# 取得扩展名
    ajaxFileUpload 注意!
    ajaxFileUpload js判断类型
    sortable items不让他拖,也不让他放。cancel不然他拖动
    json 多重嵌套反序列化和序列化
    C#串口操作类,包括串口读写操作
    C#操作Word的超详细总结
  • 原文地址:https://www.cnblogs.com/101718qiong/p/8192199.html
Copyright © 2011-2022 走看看