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()

最终截图

相关推荐
m0_7485548136 分钟前
golang如何实现用户订阅偏好管理_golang用户订阅偏好管理实现总结
jvm·数据库·python
smj2302_796826521 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
阿正呀2 小时前
Redis怎样实现本地缓存的高效失效通知
jvm·数据库·python
2501_901200532 小时前
mysql如何设置InnoDB引擎参数_优化innodb_buffer_pool
jvm·数据库·python
_.Switch2 小时前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
Mr_sst2 小时前
Claude Code 部署与使用保姆级教程(2026 最新)
python·ai
瞎某某Blinder2 小时前
DFT学习记录[6]基于 HES06的能带计算+有效质量计算
python·学习·程序人生·数据挖掘·云计算·学习方法
m0_495496413 小时前
mysql处理复杂SQL性能_InnoDB优化器与MyISAM差异
jvm·数据库·python
forEverPlume4 小时前
PHP怎么使用Eloquent Attribute Composition属性组合_Laravel通过组合构建复杂属性【方法】
jvm·数据库·python
Aleeeeex4 小时前
RAG 那点事:从 8 份企业文档到能用的问答系统,全过程拆给你看
人工智能·python·ai编程