猿问

如何使用cssSelector清除Chrome浏览器的浏览数据时,#shadow-root(打开)

我一直在讨论如何使用selenium自动化阴影DOM元素?使用#shadow-root (open)元素。


在通过Selenium访问URL时出现Clear data的清除浏览数据弹出窗口中找到按钮的过程中,我无法找到以下元素:chrome://settings/clearBrowserData


#shadow-root (open)

<settings-privacy-page>

快照:


设置 - 隐私页


使用Selenium以下是我的代码试验和遇到的相关错误:


尝试1:


WebElement root5 = shadow_root4.findElement(By.tagName("settings-privacy-page"));

错误:


Exception in thread "main" org.openqa.selenium.JavascriptException: javascript error: b.getElementsByTagName is not a function

尝试2:


WebElement root5 = shadow_root4.findElement(By.cssSelector("settings-privacy-page"));

错误:


Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"settings-privacy-page"}

尝试3:


WebElement root5 = (WebElement)((JavascriptExecutor)shadow_root4).executeScript("return document.getElementsByTagName('settings-privacy-page')[0]");

错误:


Exception in thread "main" java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to org.openqa.selenium.JavascriptExecutor

如果它有用,初始代码块(直到上面的行)完美运行:


driver.get("chrome://settings/clearBrowserData");

WebElement root1 = driver.findElement(By.tagName("settings-ui"));

WebElement shadow_root1 = expand_shadow_element(root1);


WebElement root2 = shadow_root1.findElement(By.cssSelector("settings-main#main"));

WebElement shadow_root2 = expand_shadow_element(root2);


WebElement root3 = shadow_root2.findElement(By.cssSelector("settings-basic-page[role='main']"));

WebElement shadow_root3 = expand_shadow_element(root3);


WebElement root4 = shadow_root3.findElement(By.cssSelector("settings-section[page-title='Privacy and security']"));

WebElement shadow_root4 = expand_shadow_element(root4);

PS:expand_shadow_element()工作完美无瑕。


有人可以帮帮我吗?


森林海
浏览 3052回答 3
3回答

Smart猫小萌

@ supputuri的回答是工作和接受的答案作为定位战略,通过document.querySelector()工程,经过完善的谷歌,铬devtools然而,由于所需的元素从打开阴影DOM需要引起WebDriverWait的elementToBeClickable(),你可以在你的解决方案如下:代码块:driver.get("chrome://settings/clearBrowserData");new WebDriverWait(driver, 5).until(ExpectedConditions.elementToBeClickable((WebElement) ((JavascriptExecutor)driver).executeScript("return document.querySelector('settings-ui').shadowRoot.querySelector('settings-main').shadowRoot.querySelector('settings-basic-page').shadowRoot.querySelector('settings-section > settings-privacy-page').shadowRoot.querySelector('settings-clear-browsing-data-dialog').shadowRoot.querySelector('#clearBrowsingDataDialog').querySelector('#clearBrowsingDataConfirm')"))).click();System.out.println("Clear data Button Clicked");控制台输出:Clear data Button Clicked
随时随地看视频慕课网APP
我要回答