我正在从多个网页链接下载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)
发布于 2020-04-25 09:52:45
我建议把这行改一下:
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
。
希望能有所帮助。
https://stackoverflow.com/questions/61419872
复制相似问题