Python3:将其他列表中的名称分配给一个名为其他名称的文件



当循环浏览电子邮件的html数据时,我会抓取到每个文本的超链接,当它保存时,它会作为一个嵌入文件,链接名称在目录中为httpgooglecom2021。但是,我想用来自单独列表的适当名称覆盖文件。即httpgooglecom2021 to poster.pdf

下面获取电子邮件的html数据并删除所有空白。

links = [elem.strip().split('rn')for elem in message.body['html']]

在这里,代码循环遍历html数据,并使用regex找到嵌入链接所在的地址栏,并将其下载到下载文件夹,以及查找其实际名称的纯文本。代码中的第三个for循环似乎是我的问题,它将用相同的名称覆盖每个文件,从而只创建一个文件。

for index, b in enumerate(links):
try:
hyperlinks = re.findall("(?P<url>https?://[^s]+)", str(b))
filenames= re.findall("w+.pdf|w+.jpg|w+.png|w+.jpeg",str(b))
pdf_fn = temp
for url in hyperlinks:
index = ''.join(e for e in url if e.isalnum())
for name in filenames:
index2 = ''.join(map(str,name))
download_link = f"{path}/{name}"
r = requests.get(url, allow_redirects=True)
if r.status_code == 200:
with open(download_link, 'wb') as fp:
for data in r.iter_content(chunk_size=1024* 8):
fp.write(data)
fp.flush()
os.fsync(fp.fileno())
else:
print("CANNOT DOWNLOAD FILE!! status code: {}n{}".format(r.status_code,r.text))
except:
pass
print(traceback.print_exc())

事实上,我发现从for循环到while循环只是一个简单的改变,所以

while (i < len(hyperlinks)):
download_link = f"{path}/{filenames[i]}"
r = requests.get(hyperlinks[i], allow_redirects=True)
if r.status_code == 200:
with open(download_link, 'wb') as fp:
for data in r.iter_content(chunk_size=1024* 8):
fp.write(data)
fp.flush()
os.fsync(fp.fileno())
else:
print("CANNOT DOWNLOAD FILE!! status code: {}n{}".format(r.status_code,r.text))
i += 1

相关内容

最新更新