我正在尝试使用Selenium操纵" chrome://downloads/
" URL,我的目标是开始下载,确保下载开始并取消下载。但是我无法获取下载值或取消。
说我的ID不正确,但我很确定它是正确的。有谁知道这种页面是否有任何限制?
我的代码是——
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
namespace SitesApplications
{
class Program
{
static void Main(string[] args)
{
BrowseUrl.driver = new ChromeDriver();
//ChromeOptions TESTE = new ChromeOptions();
//TESTE.AddArgument("--disable-privacy");
FileDownload teste = new FileDownload("http://centos.ufes.br/7/isos/x86_64/CentOS-7-x86_64-Everything-1708.iso", 60);
teste.gotoDownloadList("chrome://downloads/", 60);
//ChromeWebElement haha = new ChromeWebElement(BrowseUrl.DriverChrome, "pause-or-resume");
////haha.Clicks(20);
//haha.Cliquei(20);
teste.CancelaTeste(10);
}
}
程序调用
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SitesApplications
{
class FileDownload
{
/// <summary>
/// Enta no link direto para o download.
/// </summary>
/// <param name="Url">Link de destino para o download.</param>
/// <param name="time">Tempo maximo para abertura da pagina.</param>
public FileDownload(string Url, int time)
{
BrowseUrl CentOs = new BrowseUrl(Url, time);
PageFactory.InitElements(BrowseUrl.driver, this);
}
public void gotoDownloadList(string url, int timeout)
{
BrowseUrl downList = new BrowseUrl(url, timeout);
PageFactory.InitElements(BrowseUrl.driver, this);
}
private bool barra_prog;
public bool barraprog
{
get { return barra_prog; }
}
// Cancela Download
[FindsBy(How = How.TagName, Using = "Cancelar")]
public IWebElement btnCancelD { get; set; }
// Status do Download
[FindsBy(How = How.Id, Using = "description")]
public IWebElement status { get; set; }
/// Cancela teste de download
public bool CancelaTeste(int timeout)
{
BrowseUrl.driver.SwitchTo().Window("");
//barra_prog = GetElements.GetCheckBoxAttribute(status, timeout);
btnCancelD.Clicks(timeout);
//BrowseUrl.driver.Close();
//BrowseUrl.driver.Quit();
return barra_prog;
}
}
要知道如何处理这个Chrome下载页面,你必须知道如何处理Shadow DOM元素。在我最终设法让下面的解决方案工作之前,我尝试了很多不同的解决方案:
IJavaScriptExecutor jse2 = (IJavaScriptExecutor)Driver;
jse2.ExecuteScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('downloads-item').shadowRoot.getElementById('cancel').click()");
在您的情况下,您必须将"取消"替换为"取消"。这个答案是基于这个Stackoverflow问题的答案之一:使用Selenium访问Shadow DOM树
你可以在这里阅读一篇关于Shadow DOM Elements的有趣文章:http://www.seleniumeasy.com/selenium-tutorials/accessing-shadow-dom-elements-with-webdriver