如何使用jquery和selenium在'chrome:// downloads'下访问`shadow-root`下的元素?

我想在我的seleniumJavaScript应用程序中获取最后下载的文件的名称。

我有我的selenium驱动程序导航到铬下载页面使用: driver.get('chrome://downloads'); ,但是当我到达那里时,selenium在下载页面上无法find任何元素。

Chrome下载页面“chrome:// downloads”有一堆shadow-root元素,我不知道如何获取下面的内容以访问我想要的id。 如何访问shadow-root项目下的标识符?

我想获得$(“#文件链接”)如下所示:

显示文件链接ID

但是,当我使用jQuery来find它,一切都返回null(可能是因为它是在shadow-root后面)

jQuery的动作返回null jQuery的行动返回null 2

下面是我所有的信息的全貌,包括显示“#file-link”完全存在:

Chrome下载页面的html结构

我用来等待元素存在的代码与我在应用程序中使用的所有元素相同,所以我认为这已经在工作:

 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? :( }); }); 

这是我的版本信息:

  • Chromium v​​54.0.2840.71
  • 节点v6.5.0
  • ChromeDriver v2.27.440175
  • selenium-Webdriver v3.4.0

类似的问题

  • seleniumwebdriver找不到铬://下载 (这是我有,但在Python中相同的问题)

链接

  • Selenium JavaScript API: https : //seleniumhq.github.io/selenium/docs/api/javascript/

你的例子中的$不是JQuery的缩写。 它的function被页面覆盖,只通过id来定位一个元素:

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

要通过阴影DOMselect,您需要使用'/ deep /'组合子。

所以要获得下载页面中的所有链接:

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

与selenium:

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

为什么不直接检查下载文件夹? 我这样做是为了下载Excel文件。 首先清除下载文件夹,单击button下载文件,等待约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 ""; } } 

然后在我的testing中,我可以Assert.IsEmpty(LocateDownloadedFile); 这样,如果断言失败,错误消息,如果打印。

预期:String.Empty。 实际:没有文件存在。