【问题标题】:Renaming the file downloaded with Python Requests重命名使用 Python 请求下载的文件
【发布时间】:2017-10-20 07:14:34
【问题描述】:

如何替换使用 Python 请求下载的 pdf 文件的名称?

我想将其保存为Manual_name1.pdf 而不是Elkinson%20Jeffrey.pdf

CSV 文件如下所示:

Manual_name1 https://www.adndrc.org/diymodule/doc_panellist/Elkinson%20Jeffrey.pdf
Manual_name2 http://www.parliament.bm/uploadedFiles/Content/House_Business/Presentation_of_Papers_and_of_Reports/PCA%20Report%209262014.pdf
manual_name3 http://www.ohchr.org/Documents/HRBodies/OPCAT/elections2016/HaimoudRamdan.pdf

我当前的代码:

import os
import csv
import requests

write_path = 'C:\\Users\\hgdht\\Desktop\\Downloader_Automation'  # ASSUMING THAT FOLDER EXISTS!

with open('Links.csv', 'r') as csvfile:
    spamreader = csv.reader(csvfile)
    for link in spamreader:
        if not link:
            continue
        print('-'*72)
        pdf_file = link[0].split('/')[-1]
        with open(os.path.join(write_path, pdf_file), 'wb') as pdf:
            try:
                # Try to request PDF from URL
                print('TRYING {}...'.format(link[0]))
                a = requests.get(link[0], stream=True)
                for block in a.iter_content(512):
                    if not block:
                        break

                    pdf.write(block)
                print('OK.')
            except requests.exceptions.RequestException as e:  # This 
will catch ONLY Requests exceptions
                print('REQUESTS ERROR:')
                print(e)  # This should tell you more details about the error

【问题讨论】:

    标签: python python-3.x web-scraping python-requests


    【解决方案1】:

    代替

    pdf_file = link[0].split('/')[-1]
    

    使用 csv 文件中的特定列:

    pdf_file = link[1]  # (assuming the file name is in the second column)
    

    如果文件名在第一列,你应该使用

    pdf_file = link[0]  # (assuming the file name is in the first column)
    # OR
    import time  # put this in the beginning of your script
    pdf_file = '{}-{}.pdf'.format(link[0], int(time.time()))
    # file name will look like: "name-1495460691.pdf"
    

    但是当你使用请求调用它时,你将不得不更改对链接本身的引用:

    a = requests.get(link[1], stream=True)  # (assuming the link is in the second column)
    

    【讨论】:

    • 它的工作。但是,它在没有任何filetype 的情况下保存,如果我在第 1 列中有 2 个或 3 个相同的名称,它会一次又一次地替换文件 + 我如何将 timestamp 放在文件名中,这样它就不会替换具有相同名称的文件。 @勘误
    • @WarLock 当然它会替换具有相同名称的文件 :) 您必须确保所有名称都是唯一的。这是每个操作系统的“功能”......我通过在每个文件名中添加时间戳来更新我的答案。
    • 如果我们在同一 manual_name 前面的 B、C、D 列中也有多个链接,并将其保存为 save name 。我们怎么也能读到那个链接。 @勘误
    • @WarLock 文件中的每一行都是Python list,您可以像访问任何其他列表一样访问元素。另外,请避免对问题/答案进行大量评论,因为这不是 StackOverflow 的目的 (read on bottom about when you should/shouldn't comment)。在提问之前提出一个新问题或进行适当的研究;)
    • 请原谅我。下次我会记住的。 :) @勘误
    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 2013-05-17
    相关资源
    最近更新 更多