python下载pdf资源代码

python 复制代码
from datetime import datetime
import requests
import sys
from pyquery import PyQuery as pq
import os
import time
path='./book'
baseUrl = 'http://124.223.24.112:8083'
host = f'{baseUrl}/'
host1=f'{host}book/'
ls=[]
def count_files_in_directory(directory):
    # 统计给定目录中的文件个数
    return len([f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))])
def downBook():
    if not os.path.exists(path):
        os.makedirs(path, exist_ok=True)
    page =7
    headers={
        'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.40'
    }
    for i in range(1,page+1):
        url = f"http://124.223.24.112:8083/page/${page}?data=root&sort_param=stored"
        content=requests.get(url,headers=headers)
        pq1=pq(content.text).find('.author-name')
        for k in pq1:
            j=host1+k.attrib['href'].split('/')[-1]
            ls.append(j)
    if len(ls):
        for i in ls:
            time.sleep(1)
            childUrl(i)
    num_files = count_files_in_directory(path)
    print(f"所有文件下载完成,'./book' 目录中总共有 {num_files} 个文件。")

def childUrl(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.40'
    }
    content = requests.get(url, headers=headers)
    href2 = pq(content.text).find('#btnGroupDrop1pdf').attr('href')
    if not href2:
        print('没有下载地址')
        return
    bb1 = baseUrl + href2
    js = href2.split('/')[-1]

    # 检查文件是否已存在
    target_file_path = os.path.join(path, js)
    if os.path.exists(target_file_path):
        local_file_size = os.path.getsize(target_file_path)

        response = requests.head(bb1, headers=headers)
        remote_file_size = int(response.headers.get('content-length', 0))

        # 检查本地文件和远程文件的大小是否匹配
        if local_file_size == remote_file_size:
            print(f"文件 {js} 已经存在并且是完整的,跳过下载。")
            return
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    print(f'正在下载 {js} 的书籍,当前时间:{current_time}')
    response = requests.head(bb1, headers=headers)
    file_size = int(response.headers.get('content-length', 0))

    down_size = 0
    progress_len = 100

    bdata = requests.get(bb1, headers=headers, stream=True)

    with open(path + '/' + js, 'wb') as f:
        for chunk in bdata.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
                down_size += len(chunk)
                progress = int(progress_len * down_size / file_size)

                # 格式化文件大小和已下载大小
                formatted_file_size = format_size(file_size)
                formatted_down_size = format_size(down_size)

                sys.stdout.write(f'\r[{"=" * progress}{"~" * (progress_len - progress)}] {progress}% ({formatted_down_size}/{formatted_file_size})')
                sys.stdout.flush()
        # 检查是否下载完成
        if progress == 100:
            print(f'\n下载 {js} 书籍完成')
    print(f'\n下载 {js} 书籍完成')
def format_size(bytes):
    # 将字节转换为更易读的单位(KB、MB等)
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if bytes < 1024.0:
            break
        bytes /= 1024.0
    return f"{bytes:.2f} {unit}"
if __name__ == '__main__':
    downBook()

最终截图

相关推荐
弱冠少年21 分钟前
websockets库使用(基于Python)
开发语言·python·numpy
没有余地 EliasJie30 分钟前
Windows Ubuntu下搭建深度学习Pytorch训练框架与转换环境TensorRT
pytorch·windows·深度学习·ubuntu·pycharm·conda·tensorflow
技术无疆1 小时前
【Python】Streamlit:为数据科学与机器学习打造的简易应用框架
开发语言·人工智能·python·深度学习·神经网络·机器学习·数据挖掘
羊小猪~~1 小时前
机器学习/数据分析--用通俗语言讲解时间序列自回归(AR)模型,并用其预测天气,拟合度98%+
人工智能·python·机器学习·数据挖掘·数据分析·回归·时序数据库
qq_273900231 小时前
解析TMalign文本文件中的转换矩阵
python·生物信息学
阿华的代码王国2 小时前
【JavaEE】——文件IO的应用
开发语言·python
电饭叔2 小时前
《python语言程序设计》2018版第8章19题几何Rectangle2D类(下)-头疼的几何和数学
开发语言·python
程序猿小D3 小时前
第二百六十七节 JPA教程 - JPA查询AND条件示例
java·开发语言·前端·数据库·windows·python·jpa
杰哥在此4 小时前
Python知识点:如何使用Multiprocessing进行并行任务管理
linux·开发语言·python·面试·编程
zaim16 小时前
计算机的错误计算(一百一十四)
java·c++·python·rust·go·c·多项式