您不能通过selenium指定下载文件的名称.但是,您可以下载该文件,在下载的文件夹中查找最新文件,然后根据需要重命名.
注意:谷歌搜索中借用的方法可能有错误.但是你明白了.
import os import shutil filename = max([Initial_path + "\\" + f for f in os.listdir(Initial_path)],key=os.path.getctime) shutil.move(filename,os.path.join(Initial_path,r"newfilename.ext"))
我会针对@parishodak答案进行一些更正:
此处的文件名将仅返回相对路径(此处为文件名),而不是绝对路径。
这就是为什么@FreshRamen之后出现以下错误:
File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/??python2.7/genericpath.py", line 72, in getctime return os.stat(filename).st_ctime OSError: [Errno 2] No such file or directory: '.localized'
有正确的代码:
import os import shutil filepath = 'c:\downloads' filename = max([filepath +"\"+ f for f in os.listdir(filepath)], key=os.path.getctime) shutil.move(os.path.join(dirpath,filename),newfilename)
这是另一个简单的解决方案,您可以等到下载完成后再从chrome下载中获取下载的文件名。
铬:
# method to get the downloaded file name def getDownLoadedFileName(waitTime): driver.execute_script("window.open()") # switch to new tab driver.switch_to.window(driver.window_handles[-1]) # navigate to chrome downloads driver.get('chrome://downloads') # define the endTime endTime = time.time()+waitTime while True: try: # get downloaded percentage downloadPercentage = driver.execute_script( "return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value") # check if downloadPercentage is 100 (otherwise the script will keep waiting) if downloadPercentage == 100: # return the file name once the download is completed return driver.execute_script("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').text") except: pass time.sleep(1) if time.time() > endTime: break
Firefox:
def getDownLoadedFileName(waitTime): driver.execute_script("window.open()") WebDriverWait(driver,10).until(EC.new_window_is_opened) driver.switch_to.window(driver.window_handles[-1]) driver.get("about:downloads") endTime = time.time()+waitTime while True: try: fileName = driver.execute_script("return document.querySelector('#contentAreaDownloadsView .downloadMainArea .downloadContainer description:nth-of-type(1)').value") if fileName: return fileName except: pass time.sleep(1) if time.time() > endTime: break
单击下载链接/按钮后,只需调用上述方法即可。
# click on download link browser.find_element_by_partial_link_text("Excel").click() # get the downloaded file name latestDownloadedFileName = getDownLoadedFileName(180) #waiting 3 minutes to complete the download print(latestDownloadedFileName)
JAVA + Chrome:
这是java中的方法。
public String waitUntilDonwloadCompleted(WebDriver driver) throws InterruptedException { // Store the current window handle String mainWindow = driver.getWindowHandle(); // open a new tab JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("window.open()"); // switch to new tab // Switch to new window opened for(String winHandle : driver.getWindowHandles()){ driver.switchTo().window(winHandle); } // navigate to chrome downloads driver.get("chrome://downloads"); JavascriptExecutor js1 = (JavascriptExecutor)driver; // wait until the file is downloaded Long percentage = (long) 0; while ( percentage!= 100) { try { percentage = (Long) js1.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value"); //System.out.println(percentage); }catch (Exception e) { // Nothing to do just wait } Thread.sleep(1000); } // get the latest downloaded file name String fileName = (String) js1.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').text"); // get the latest downloaded file url String sourceURL = (String) js1.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').href"); // file downloaded location String donwloadedAt = (String) js1.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div.is-active.focus-row-active #file-icon-wrapper img').src"); System.out.println("Download deatils"); System.out.println("File Name :-" + fileName); System.out.println("Donwloaded path :- " + donwloadedAt); System.out.println("Downloaded from url :- " + sourceURL); // print the details System.out.println(fileName); System.out.println(sourceURL); // close the downloads tab2 driver.close(); // switch back to main window driver.switchTo().window(mainWindow); return fileName; }
这是在您的Java脚本中调用此方法的方法。
// download triggering step downloadExe.click(); // now waituntil download finish and then get file name System.out.println(waitUntilDonwloadCompleted(driver));
输出:
下载详细信息
文件名:-RubyMine-2019.1.2(7).exe
下载的路径:-chrome://fileicon/C%3A%5CUsers%5Csupputuri%5CDownloads%5CRubyMine-2019.1.2%20(7).exe?scale = 1.25x
从URL下载:-https: //download-cf.jetbrains.com/ruby/RubyMine-2019.1.2.exe
RubyMine-2019.1.2(7).exe