Python脚本:自动化检测并下载更新的PDF文件
这个脚本使用Python来定期检查指定网站上是否有新的PDF文件,并自动下载它们。以下是实现此功能的步骤和代码示例。
1. 安装必要的库
首先,你需要安装以下Python库:
requests
: 用于发送HTTP请求以下载网页和文件。beautifulsoup4
: 用于解析HTML页面,查找PDF链接。schedule
: 用于定期运行检查更新的任务。
你可以使用pip来安装它们:
pip install requests beautifulsoup4 schedule
2. 编写Python脚本
下面是一个示例脚本,它将定期检查网站并下载新的PDF文件:
import requests
from bs4 import BeautifulSoup
import os
import schedule
import time
import logging
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# 目标网站和下载目录
WEBSITE_URL = 'http://example.com/pdf_directory/' # 替换为你的目标网站
DOWNLOAD_DIR = 'downloaded_pdfs'
# 确保下载目录存在
if not os.path.exists(DOWNLOAD_DIR):
os.makedirs(DOWNLOAD_DIR)
# 已下载的文件列表
downloaded_files = set()
# 从文件加载已下载的文件列表
def load_downloaded_files():
global downloaded_files
try:
with open('downloaded_files.txt', 'r') as f:
downloaded_files = set(f.read().splitlines())
logging.info(f'Loaded {len(downloaded_files)} downloaded files from file.')
except FileNotFoundError:
logging.info('downloaded_files.txt not found, starting with an empty list.')
# 保存已下载的文件列表到文件
def save_downloaded_files():
with open('downloaded_files.txt', 'w') as f:
f.write('\n'.join(downloaded_files))
logging.info(f'Saved {len(downloaded_files)} downloaded files to file.')
# 下载PDF文件
def download_pdf(pdf_url):
filename = os.path.join(DOWNLOAD_DIR, pdf_url.split('/')[-1])
try:
response = requests.get(pdf_url, stream=True)
response.raise_for_status() # 检查HTTP错误
with open(filename, 'wb') as pdf_file:
for chunk in response.iter_content(chunk_size=8192):
pdf_file.write(chunk)
logging.info(f'Downloaded {filename}')
downloaded_files.add(pdf_url)
save_downloaded_files()
except requests.exceptions.RequestException as e:
logging.error(f'Download failed for {pdf_url}: {e}')
# 检查更新
def check_for_updates():
logging.info('Checking for updates...')
try:
response = requests.get(WEBSITE_URL)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
pdf_links = [WEBSITE_URL + a['href'] for a in soup.find_all('a', href=lambda href: href and href.endswith('.pdf'))]
new_pdfs = [pdf_url for pdf_url in pdf_links if pdf_url not in downloaded_files]
if new_pdfs:
logging.info(f'Found {len(new_pdfs)} new PDFs.')
for pdf_url in new_pdfs:
download_pdf(pdf_url)
else:
logging.info('No new PDFs found.')
except requests.exceptions.RequestException as e:
logging.error(f'Failed to check for updates: {e}')
# 任务调度
def schedule_tasks():
load_downloaded_files()
schedule.every(1).hour.do(check_for_updates)
logging.info('Scheduler started.')
while True:
schedule.run_pending()
time.sleep(60) # 检查频率(秒)
if __name__ == '__main__':
schedule_tasks()
3. 代码解释
- 导入库: 导入所需的库。
- 配置: 设置目标网站URL和下载目录。
download_pdf(pdf_url)
函数: 下载指定的PDF文件,处理下载错误,并将已下载的文件保存到downloaded_files.txt
文件中。check_for_updates()
函数: 获取网页内容,使用Beautiful Soup解析HTML,找到所有PDF链接,并下载新的PDF文件。schedule_tasks()
函数: 使用schedule
库来定期运行check_for_updates()
函数。- 主程序: 调用
schedule_tasks()
启动任务调度。 - 错误处理: 使用
try...except
块来捕获和处理可能出现的异常,例如网络错误。 - 日志记录: 使用
logging
模块来记录脚本的运行状态和错误信息。
4. 运行脚本
保存脚本为 .py
文件(例如 pdf_downloader.py
),然后在命令行中运行它:
python pdf_downloader.py
5. 注意事项
- 替换
WEBSITE_URL
为你要监控的实际网站地址。 - 可以根据需要调整检查更新的频率(例如,每天、每周)。
- 此脚本仅适用于简单的HTML结构。对于更复杂的网站,可能需要更复杂的解析逻辑。
- 确保你有足够的权限在指定的下载目录中创建和写入文件。
- 请遵守网站的使用条款和robots.txt协议。
这个脚本提供了一个基本的框架,你可以根据自己的需求进行修改和扩展。例如,你可以添加邮件通知功能,当有新的PDF文件下载时发送邮件通知你。