我正在从多个网络链接下载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
。
希望能有所帮助。