美文网首页大数据 爬虫Python AI Sql
python的requests模块进行下载限速

python的requests模块进行下载限速

作者: 毛毛v5 | 来源:发表于2019-12-20 13:28 被阅读0次

    python的requests模块进行下载带宽限制,进行现在速度限制,避免拉爆服务器。开启requests的stream=True就可以进行渐进式下载,然后再适当的sleep一下。就可以减少下载带宽,限制下载速度了。

                # NOTE the stream=True parameter below
                recvlen = 0
                tickss = time.time()
                with requests.get(mp3url, stream=True) as r:
                    r.raise_for_status()
                    with open(mp3f, 'wb') as f:
                        for chunk in r.iter_content(chunk_size=30720): 
                            if chunk: # filter out keep-alive new chunks
                                f.write(chunk)
                                recvlen = recvlen + len(chunk)
                                time.sleep(0.1)
                                # f.flush()
    
    
                tickse = time.time()
                #f=requests.get(mp3url)
                #with open(mp3f,"wb") as code:
                #    code.write(f.content)
                print("------------------------")
                print(title)
                print(mp3f)
                print(mp3url)
                print("长度:",recvlen)
                print("耗时:",tickse-tickss,"秒")
                print("++++++++++++++++++++++++")
                time.sleep(3)
    

    限速结果日志如下:

    长度: 2950970
    耗时: 9.922253608703613 秒
    
    长度: 3413255
    耗时: 11.447856426239014 秒
    
    长度: 3465066
    耗时: 11.52188777923584 秒
    
    长度: 5089296
    耗时: 16.877254486083984 秒
    
    长度: 2969808
    耗时: 9.891138792037964 秒
    
    长度: 5777092
    耗时: 19.198574781417847 秒
    
    长度: 6185409
    耗时: 20.51071047782898 秒
    

    相关文章

      网友评论

        本文标题:python的requests模块进行下载限速

        本文链接:https://www.haomeiwen.com/subject/zqtinctx.html