【问题标题】:How to change default download folder while webdriver is running?如何在 webdriver 运行时更改默认下载文件夹?
【发布时间】:2014-07-16 18:59:55
【问题描述】:

我正在下载几个不同的数据集,并希望将每个文件(或数据集)下载到特定文件夹。我已经学会了如何在这些页面上更改下载目录:

setting Chrome preferences w/ Selenium Webdriver in Python

Change the default chrome download folder webdriver C#

问题是这些方法只允许我在打开 webdriver 时更改下载目录。到达下载页面需要一段时间,因此这样做是一种无效的解决方案。我已经尝试过设置首选项,但我在 python 中使用 selenium webdriver 和 chrome,我无法在 SO 或 python 帮助中找到任何内容。即使在新驱动程序上切换窗口句柄也不起作用,因为它无法抓住另一个驱动程序已经打开的窗口。

下载站点的链接是自定义的,因此也无法复制并粘贴到新的驱动程序中。到目前为止,我一直在使用操作系统。模块来获取每个新文件的名称,但由于下载时间不同,即使这样也不可靠。

如果有人知道如何在 webdriver 运行时将默认设置更改为 webdriver,那就太好了。谢谢!

【问题讨论】:

    标签: python google-chrome selenium download preferences


    【解决方案1】:

    我使用了 chromeOptions 实验方法。

    ##set download directory
    chromeOptions = webdriver.ChromeOptions()
    prefs = {"download.default_directory": "your directory path"}
    chromeOptions.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', 
    chrome_options=chromeOptions)
    

    在本例中,我的 chromedriver 位于 /usr/bin 中。唯一的缺点是您必须根据浏览器更新使您的 chromedriver 保持最新。因此,当您更新浏览器时,您必须更新 chromedriver。

    这对我有用。

    【讨论】:

      【解决方案2】:

      过去,我通过下载到一个临时文件夹然后将文件重命名为相应的文件夹来解决这个问题:

      def move_to_download_folder(downloadPath, newFileName, fileExtension):
          got_file = False   
          ## Grab current file name.
          while got_file = False:
              try: 
                  currentFile = glob.glob(DOWNLOAD_PATH+"*"+fileExtension)
                  got_file = True
      
              except:
                  print "File has not finished downloading"
                  time.sleep(20)
      
          ## Create new file name
          fileDestination = downloadPath+newFileName+fileExtension
      
          os.rename(currentFile, fileDestination)
      
          return
      
      ## Click element to download file
      inputElement=driver.find_element_by_xpath("{xpath here}").click()
      
      move_to_download_folder(downloadPath, newFileName, fileExtension)
      

      【讨论】:

      • 酷,我在 while 循环中使用了 glob.glob,除了我只是检查该扩展名下是否有新文件,因为下载路径和文件名不匹配。聪明,谢谢!
      • For/else 使它更简洁一些并添加错误处理:for _ in xrange(20): try: currentFile = glob.glob(DOWNLOAD_PATH+"*"+fileExtension) break except: print "File has not finished downloading" time.sleep(1) else: raise Exception("Could not download document with path {0}".format(DOWNLOAD_PATH) 编辑:...hmmm 在评论中绝对不干净,但希望你明白我的意思。 ;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 2016-03-28
      相关资源
      最近更新 更多