[英]Renaming pdf files when being downloaded
我正在从多个网络链接下载 pdf 个文件(每个链接一个 pdf),并希望使用一系列值重命名每个 pdf 文件,以便可以唯一标识它们。 我正在使用以下代码,但是当下载 pdf 个文件时,所有文件都称为multi-page
文件,因此文件夹中只保留一个文件。 我想要 pdf 个文件名以 1 开头,然后为每个文件添加 1(+1),即 2、3、4、5 等)。
import os
import time
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
url = ["http://example1.com",
"http://example2.com",
"http://example3.com",
"http://example4.com"]
folder_location = r'K:/example'
for i in url:
time.sleep(10)
response = requests.get(i)
soup= BeautifulSoup(response.text, "lxml")
for link in soup.select("[href$='.pdf']"):
filename = os.path.join(folder_location,link['href'].split('/')[-1])
with open(filename, 'wb') as f:
f.write(requests.get(urljoin(i,link['href'])).content)
我建议更改行:
filename = os.path.join(folder_location,link['href'].split('/')[-1])
到:
filename = os.path.join(folder_location,"{}_{}".format(i, link['href'].split(os.sep)[-1]))
注意:变量i
应该为每个 pdf 提供不同的名称。我还将/
更改为独立于操作系统的os.sep
。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.