【问题标题】:(Selenium) Download and Rename File Problem(Selenium) 下载和重命名文件问题
【发布时间】:2019-03-12 03:21:41
【问题描述】:

我正在使用selenium 登录一个页面,并下载一些 tiff 文件, 现在我有一个变量downloadurl,它包含我从网站上抓取的一组 url 链接。现在我正在使用以下代码下载文件:

 driver = webdriver.Chrome();
 driver.get(downloadurl)

我确实下载了所有文件但没有名称,例如。图像(1),图像(2) ...

现在我的问题是:我想driver.get(downloadurl)按照downloadurl的数组顺序一个一个下载文件,下载后马上按照数组的title变量重命名文件,然后下载下一个文件,然后重命名...

P.S.我避免使用请求,因为登录过程非常复杂并且需要授权cookie。

非常感谢您的帮助!

【问题讨论】:

  • 如果您知道它最初会保存为img(1),只需让您的脚本下载文件,然后将os.rename() 文件从“img(1)”保存到其他文件。然后冲洗并重复,因为它们都将使用相同的名称下载。 docs.python.org/3/library/os.html#os.rename

标签: python selenium web-scraping beautifulsoup python-requests


【解决方案1】:

详细说明我的评论:

import os
import time

for downloadlink, uniqueName in my_list_of_links_and_names:
    driver = webdriver.Chrome();
    driver.get(downloadurl)
    time.sleep(5) # give it time to download (not sure if this is necessary)
    # the file is now downloaded
    os.rename("img(1).png", uniqueName) # the name is now changed

假设“img(1).png”将被重命名,然后下一次下载将再次以“img(1).png”的形式出现。

最困难的部分是创建my_list_of_links_and_names,但如果您将数据放在单独的列表中,只需将zip() 放在一起即可。您还可以根据某些标准在每个循环中生成自己的标题...

【讨论】:

    【解决方案2】:

    首先,我们将创建一个函数(Rename_file),从其文件夹中重命名下载的图像。

    def Rename_file(new_name, Dl_path):  #Renames Downloaded Files in the path
        filename = max([f for f in os.listdir(Dl_path)])
        if 'image.png' in filename: #Finds 'image.png' name in said path
                time.sleep(2) #you can change the value in here depending on your requirements
                os.rename(os.path.join(Dl_path, filename), os.path.join(Dl_path, new_name+'.png')) #can be changed to .jpg etc
    

    然后我们在 url 链接数组中应用这个函数:

    for link in downloadurl: #Will get each link in download url array
        for new_name in title:
                driver.get(link) #download the said image in link
                Rename_file(new_name,Dl_path)
    

    示例代码:

    downloadurl = ['www.sample2.com','www.sample2.com'] 
    Dl_path  = "//location//of//image_downloaded"
    title  = ['Title 1', 'Title 2']
    
    def Rename_file(new_name, Dl_path):  
        filename = max([f for f in os.listdir(Dl_path)])
        if 'image.png' in filename: 
                time.sleep(2)
                os.rename(os.path.join(Dl_path, filename), os.path.join(Dl_path, new_name+'.png'))
    
    for new_name in title:
       for link in downloadurl: 
                driver.get(link) 
                time.sleep(2)
                Rename_file(new_name,Dl_path)
    

    我很确定我创建的重命名函数,但我还没有用一组 url 链接真正测试过它,因为我真的想不出在哪里可以测试它。希望这对你有用。请告诉我:-)

    【讨论】:

      猜你喜欢
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      相关资源
      最近更新 更多