2017-06-06 263 views
2

我想在我的selenium javascript應用程序中獲取上次下載的文件的名稱。如何使用jquery和selenium在'chrome:// downloads'處訪問`shadow-root`下的元素?

我有我的硒驅動程序導航到鉻下載頁使用:driver.get('chrome://downloads');,但是當我到達那裏時,硒無法找到下載頁面上的任何元素。

鉻下載頁的Chrome://下載「有一堆的,我不知道如何才能訪問ID的,我希望得到下面shadow-root元素。 如何訪問shadow-root項目下的標識符?

我想$( 「#文件鏈接」),如下所示:

showing file link id

但是,當我使用jQuery找到它,一切都返回null(可能是因爲它的背後shadow-root

jquery actions return null jquery actions return null 2

這裏的一切我都包括顯示出「#文件鏈接」的信息的大圖像t otally存在:

html structure of chrome download page

我使用等待存在的元素的代碼是一樣的,我用在我的應用程序的所有元素,所以我覺得這個已經工作:

driver.wait(until.elementLocated(By.id('downloads-manager')), 120000).then(function(){ 
    console.log("#downloads-manager shows"); 
    driver.findElement(By.id('downloads-manager')).then(function(dwMan){ 
     //How do I "open" #shadow-root now? :(
    }); 
}); 

這裏是我的版本信息:

  • 鉻v54.0.2840.71
  • 節點V6.5.0
  • ChromeDriver v2.27.440175
  • 硒的webdriver v3.4.0

類似的問題

鏈接

回答

3

$從你的例子不是JQuery的簡寫。 它的功能在頁面重載僅ID來定位一個元素:

function $(id){var el=document.getElementById(id);return el?assertInstanceof(el,HTMLElement):null} 

要通過影子DOM選擇,你需要使用「/深/」的組合子。

因此,要獲得在下載頁面中的所有鏈接:

document.querySelectorAll("downloads-manager /deep/ downloads-item /deep/ [id=file-link]") 

而且隨着硒:

By.css("downloads-manager /deep/ downloads-item /deep/ [id=file-link]") 
+0

Oooooh哇,更有意義!謝謝Florent! – Kayvar

0

爲什麼不檢查直接下載文件夾?我這樣做是爲了下載Excel文件。首先清除下載文件夾,單擊按鈕下載文件,等待約5秒(根據文件大小,網速等因素而定),然後在文件夾中查找「* .xlsx」文件。這也有利於使用任何瀏覽器。

C#示例:

/// <summary> 
/// Deletes the contents of the current user's "Downloads" folder 
/// </summary> 
public static void DeleteDownloads() 
{ 
    // Get the default downloads folder for the current user 
    string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads"; 
    // Delete all existing files 
    DirectoryInfo di = new DirectoryInfo(directoryPath); 
    foreach (FileInfo file in di.GetFiles()) 
    { 
     file.Delete(); 
    } 
    foreach (DirectoryInfo dir in di.GetDirectories()) 
    { 
     dir.Delete(true); 
    } 
} 

/// <summary> 
/// Looks for a file with the given extension (Example: "*.xlsx") in the current user's "Download" folder. 
/// </summary> 
/// <returns>Empty string if files are found</returns> 
public static string LocateDownloadedFile(string fileExtension) 
{ 
    // Get the default downloads folder for the current user 
    string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads"; 
    DirectoryInfo di = new DirectoryInfo(downloadFolderPath); 
    FileInfo[] filesFound = di.GetFiles(fileExtension); 
    if (filesFound.Length == 0) 
    { 
     return "No files present"; 
    } 
    else 
    { 
     return ""; 
    } 
} 

然後在我的測試,我可以Assert.IsEmpty(LocateDownloadedFile);如果這樣的斷言失敗,如果打印錯誤消息。

預期:String.Empty。 實際:沒有文件存在。

+0

謝謝!是的,這可能是一個更好的方法。我認爲鉻是下載所有用戶文件的地方有一個變量,所以我可以檢查最近是否有文件下載。我會嘗試這種方法,看看它是否更容易工作:) – Kayvar

相關問題