request保存图片

requests.get获取要下载的资源,stream=True打开流下载,用于保存图片

with...as...自动关闭流,上下文管理器创建的前提类实现了__enter__() __exit__()这两个方法

新版本的request库可以直接用with...as...自动关闭流,而旧版本的request库并没有这2个方法,所以这里可以用contentlib.closing自动为它创建__enter__() __exit__()这两个方法

resp.iter_content遍历数据块,可选参数chunk_size必须是int或者None

def download_image():
    # resp = requests.get(url, stream=True)
    # from contextlib import closing
    # with closing(requests.get(url, stream=True)) as resp:
    with requests.get(url, stream=True) as resp:
        with open('demo.jpg', 'wb') as fd:
            for chunk in resp.iter_content():
                fd.write(chunk)
    # print(resp.text)
    print(resp.request.headers)
    print(resp.status_code)

实例:抓取简书网页内图片

import re
import requests
from bs4 import BeautifulSoup

def check_image_element(tag): # 判断满足要求img元素
    return tag.name == 'img' and tag.has_attr('data-original-src')

def get_jianshu_image_links(URL, headers):

    resp = requests.get(URL, headers=headers) # 抓取网页
    soup = BeautifulSoup(resp.text, 'html.parser')
    imgs = soup.find_all(check_image_element) # 寻找满足要求的元素
    for img in imgs:
        download_jianshu_image('https:' + img['data-original-src'], headers)

def download_jianshu_image(URL, headers):

    print(URL)
    filename = re.search('\d+\-[0-9a-z]+\.jpg', URL).group() # 匹配图片名
    print(filename)

    # 抓取图片网页,打开流传输,可避免大量数据立即读入内存
    with requests.get(URL, headers=headers, stream=True) as resp:
        with open(filename, 'wb') as fd: # 打开文件
            for chunk in resp.iter_content(128):
                fd.write(chunk)    # 存入数据块
    '''
    with requests.get(URL, headers=headers) as resp:
        with open(filename, 'wb') as fd:  # 打开文件
            fd.write(resp.content)  # 存入数据块
    '''

if __name__=='__main__':
    strat_url = 'https://www.jianshu.com/p/1376959C3679'
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3679.0 Safari/537.36'}
    get_jianshu_image_links(strat_url, headers)

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值