python 下载PDF学习笔记

该文介绍了两种使用Python下载PDF文件的方法:一是通过BytesIO将响应内容转换为二进制流并写入文件;二是利用response.iter_content()遍历内容并逐块写入。这两种方法都需要将HTTP响应内容处理为二进制格式。
摘要由CSDN通过智能技术生成
python下载PDF

前置步骤同普通下载txt等文件一致,在数据抓取后需要转为二进制字节流形式保存,写入也要用二进制写入到新的pdf文件。

示例1 利用io转二进制
import io
import requests
def download_pdf(save_path,pdf_name,pdf_url):
    send_headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
        "Connection": "keep-alive",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.8"}
    response = requests.get(pdf_url, headers=send_headers)
    bytes_io = io.BytesIO(response.content)#转二进制
    with open(save_path + "%s.PDF" % pdf_name, mode='wb') as f:
        f.write(bytes_io.getvalue())#写入
        print('%s.PDF,下载成功!' % (pdf_name))
示例2 利用response.iter_content()遍历response.content
def download_all_pdf_files(url, pdfs):
    print("The following pdf files are downloaded from", url)
    for index, pdf in enumerate(pdfs, 1):
        print("%d. %s" %(index, pdf))
        #stream
        response = requests.get(url + pdf , stream=True)
    try:
        new_pdf_file = str(index)+'. '+pdf
        with open(new_pdf_file, 'wb') as handle:
            for block in response.iter_content(1024):#response.iter_content()遍历response.content
                handle.write(block)
    except:
        print("writing pdf file %s failed." % new_pdf_file)

代码参考:

Python怎么下载链接里的PDF?Python如何下载PDF文件

【转】Python编程: 多个PDF文件合并以及网页上自动下载PDF文件

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值