How to scoll down a web element in selenium using java? - java

I have a Javascript which is used to scroll the web element .
I want to convert it to selenium + java code.
I tried using java script executor but somehow I'm not able to get the desired result.
Here's the javascript that is working fine for me .
var x = window.content.document.getElementsByClassName("_PMgtb");
x[0].scrollTop += 100;

You can use the "org.openqa.selenium.interactions.Actions" class to move to an element:
WebElement element = driver.findElement(By.class("_PMgtb"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();

You could use
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = null;
element = (WebElement) js.executeScript("return document.getElementsByClassName("_PMgtb")[0];", element);
js.executeScript("arguments[0].scrollTop = arguments[1];",element, 100);

Related

Reach for the nested element using Selenium WebDriver (Java)

I want to click the 'Download' button on the pdf-viewer page using Selenium. This is html code of that page.
I suppose I need to use switchTo().frame() to reach for the element marked with red frame. I use the following Java code for that.
driver.switchTo().frame(driver.findElement(By.xpath("//*[#id='viewer']")));
driver.switchTo().frame(driver.findElement(By.xpath("//*[#id='toolbar']")));
driver.switchTo().frame(driver.findElement(By.xpath("//*[#id='downloads']")));
driver.findElement(By.xpath("//*[#id='download']")).click();
But it doesn't work :( Please, give me some ideas how to solve the problem. Thank you in advance!
As per the screen shot, the Element is in a shadow-root with Mode open.
To get the required element inside the shadow DOM, we need to make use of Javascript.
You can refer This Link about interacting with Shadom DOM
The code would be something like this:
public class shadowdomexample {
WebElement root1 = driver.findElement(By.id("viewer"));
//Get shadow root element
WebElement shadowRoot1 = expandRootElement(root1);
WebElement root2 = shadowRoot1.findElement(By.id("toolbar"));
WebElement shadowRoot2 = expandRootElement(root2);
WebElement root3 = shadowRoot2.findElement(By.id("downloads"));
WebElement shadowRoot3 = expandRootElement(root3);
//This should return the required Element.
WebElement DownloadsElement = shadowRoot3.findElement(By.cssSelector("cr-icon-button[id=downloads]"));
}
//Returns webelement
public WebElement expandRootElement(WebElement element) {
WebElement ele = (WebElement) ((JavascriptExecutor) driver)
.executeScript("return arguments[0].shadowRoot",element);
return ele;
}

How to interact with the elements within #shadow-root (open) while Clearing Browsing Data of Chrome Browser using cssSelector

I had been following the discussion How to automate shadow DOM elements using selenium? to work with #shadow-root (open) elements.
While in the process of locating the Clear data button within the Clear browsing data popup, which appears while accessing the url chrome://settings/clearBrowserData through Selenium I am unable to locate the following element:
#shadow-root (open)
<settings-privacy-page>
Snapshot:
Using Selenium following are my code trials and the associated errors encountered:
Attempt 1:
WebElement root5 = shadow_root4.findElement(By.tagName("settings-privacy-page"));
Error:
Exception in thread "main" org.openqa.selenium.JavascriptException: javascript error: b.getElementsByTagName is not a function
Attempt 2:
WebElement root5 = shadow_root4.findElement(By.cssSelector("settings-privacy-page"));
Error:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"settings-privacy-page"}
Attempt 3:
WebElement root5 = (WebElement)((JavascriptExecutor)shadow_root4).executeScript("return document.getElementsByTagName('settings-privacy-page')[0]");
Error:
Exception in thread "main" java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to org.openqa.selenium.JavascriptExecutor
Incase if it is helpful the initial code block (till the above line) works perfect:
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() works flawless.
If you are trying to get 'Clear Data' element then you can use the below js to get the element and then perform.
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')
Here is the sample script.
driver.get("chrome://settings/clearBrowserData");
driver.manage().window().maximize();
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement clearData = (WebElement) js.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')");
// now you can click on clear data button
clearData.click();
Edit 2: Explanation
Problem: Selenium does not provide explicit support to work with Shadow DOM elements, as they are not in the current dom. That's the reason why we will get NoSuchElementException exception when try to access the elements in the shadow dom.
Shadow DOM:
Note: We will be referring to the terms shown in the picture. So please go through the picture for better understanding.
Solution:
In order to work with shadow element first we have to find the shadow host to which the shadow dom is attached. Here is the simple method to get the shadow root based on the shadowHost.
private static WebElement getShadowRoot(WebDriver driver,WebElement shadowHost) {
JavascriptExecutor js = (JavascriptExecutor) driver;
return (WebElement) js.executeScript("return arguments[0].shadowRoot", shadowHost);
}
And then you can access the shadow tree element using the shadowRoot Element.
// get the shadowHost in the original dom using findElement
WebElement shadowHost = driver.findElement(By.cssSelector("shadowHost_CSS"));
// get the shadow root
WebElement shadowRoot = getShadowRoot(driver,shadowHost);
// access shadow tree element
WebElement shadowTreeElement = shadowRoot.findElement(By.cssSelector("shadow_tree_element_css"));
In order to simplify all the above steps created the below method.
public static WebElement getShadowElement(WebDriver driver,WebElement shadowHost, String cssOfShadowElement) {
WebElement shardowRoot = getShadowRoot(driver, shadowHost);
return shardowRoot.findElement(By.cssSelector(cssOfShadowElement));
}
Now you can get the shadowTree Element with single method call
WebElement shadowHost = driver.findElement(By.cssSelector("shadowHost_CSS_Goes_here));
WebElement shadowTreeElement = getShadowElement(driver,shadowHost,"shadow_tree_element_css");
And perform the operations as usual like .click(), .getText().
shadowTreeElement.click()
This Looks simple when you have only one level of shadow DOM. But here, in this case we have multiple levels of shadow doms. So we have to access the element by reaching each shadow host and root.
Below is the snippet using the methods that mentioned above (getShadowElement and getShadowRoot)
// Locate shadowHost on the current dom
WebElement shadowHostL1 = driver.findElement(By.cssSelector("settings-ui"));
// now locate the shadowElement by traversing all shadow levels
WebElement shadowElementL1 = getShadowElement(driver, shadowHostL1, "settings-main");
WebElement shadowElementL2 = getShadowElement(driver, shadowElementL1,"settings-basic-page");
WebElement shadowElementL3 = getShadowElement(driver, shadowElementL2,"settings-section > settings-privacy-page");
WebElement shadowElementL4 = getShadowElement(driver, shadowElementL3,"settings-clear-browsing-data-dialog");
WebElement shadowElementL5 = getShadowElement(driver, shadowElementL4,"#clearBrowsingDataDialog");
WebElement clearData = shadowElementL5.findElement(By.cssSelector("#clearBrowsingDataConfirm"));
System.out.println(clearData.getText());
clearData.click();
You can achieve all the above steps in single js call as at mentioned at the beginning of the answer (added below just to reduce the confusion).
WebElement clearData = (WebElement) js.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')");
Screenshot:
I had to do a similar test which required clearing browsing the chrome history. A minor difference was that I was clearing the data after going to the advanced section of the pop-up. As you are struggling to click only the "Clear data" button, I'm quite sure that you've missed one or two hierarchy elements mistakenly. Or got confused between sibling and parent elements probably. As per seeing your code, I assume that you already know that to access a particular shadow DOM element you need proper sequencing and it has been explained also quite nicely above.
Coming right at your problem now, here is my code snippet which is working correctly. The code waits until the data is cleaned and then will proceed to your next action-
public WebElement expandRootElement(WebElement element) {
WebElement ele = (WebElement) ((JavascriptExecutor) driver).executeScript("return arguments[0].shadowRoot",
element);
return ele;
}
public void clearBrowsingHistory() throws Exception {
WebDriverWait wait = new WebDriverWait(driver, 15);
driver.get("chrome://settings/clearBrowserData");
// Get shadow root elements
WebElement shadowRoot1 = expandRootElement(driver.findElement(By.xpath("/html/body/settings-ui")));
WebElement root2 = shadowRoot1.findElement(By.cssSelector("settings-main"));
WebElement shadowRoot2 = expandRootElement(root2);
WebElement root3 = shadowRoot2.findElement(By.cssSelector("settings-basic-page"));
WebElement shadowRoot3 = expandRootElement(root3);
WebElement root4 = shadowRoot3
.findElement(By.cssSelector("#advancedPage > settings-section > settings-privacy-page"));
WebElement shadowRoot4 = expandRootElement(root4);
WebElement root5 = shadowRoot4.findElement(By.cssSelector("settings-clear-browsing-data-dialog"));
WebElement shadowRoot5 = expandRootElement(root5);
WebElement root6 = shadowRoot5
.findElement(By.cssSelector("cr-dialog div[slot ='button-container'] #clearBrowsingDataConfirm"));
root6.click();
wait.until(ExpectedConditions.invisibilityOf(root6));
}
It should work properly in your case too if you don't intend to change any of the options selected by default in the pop-up (In that case, you will have to add a few more codes regarding selecting those checkboxes). Please tell me if this solves your issue. Hope this is helpful
I've added a snapshot of the the screen here too-
image
The Locator Strategy in #supputuri's answer using document.querySelector() works perfect through google-chrome-devtools
However, as the desired element opens from the shadow-dom you need to induce WebDriverWait for the elementToBeClickable() and you can you the following solution:
Code Block:
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");
Console Output:
Clear data Button Clicked
I was getting InvalidArgumentEXception when trying to identify shadowRoot element in DOM using Selenium 4.3.0 and Chrome Version 103.0.5060.134
The solution to this is
SearchContext se= driver.findElment(By.locator("...").getShadowRoot(); return type is SearchContext
in the above line try using locator as xpath
and secondly trying to locate element using SearchContext reference e.g.
WebElement we= se.findElement(By.locator("....."));
use locater as cssSelector
And boom it works like charm
Didn't find this solution available and took me half a day to figure out
Hope this helps!!!

Automatic Horizontal scroll not working in Selenium

I have tried many codes but none worked for me.The site is built in Angular.
WebElement columnElement = driver.findElement(By.id("i301Indv"));
((JavascriptExecutor)getDriver()).executeScript(
"arguments[0].scrollIntoView(true);", columnElement);
WebElement columnElement = driver.findElement(By.id("i301Indv"));
((JavascriptExecutor)getDriver()).executeScript(
"arguments[0].scrollIntoView();", columnElement);
WebElement columnElement = driver.findElement(By.id("i301Indv"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollLeft = arguments[0].offsetWidth", columnElement);
Try this:
Actions actions = new Actions(Webdriver);
actions.moveToElement(webElement).click().build().perform();
This will find the element, move to that element and perform the click operation.

How to scroll down of specific div to locate an element and make it clickable via selenium webdriver in java

I need to click on a button 'NEW'. The element button is visible on DOM but it's not clickable because it's overlapped and i need to scroll down left side of the page to make it clickable. I was trying inject some javascript but it didn't help in my case:
JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("scroll(" + driver.findElement(By.xpath(//div[#class = 'save-new'])).getLocation().getX() + "," + driver.findElement(By.xpath(//div[#class = 'save-new'])).getLocation().getY() + ")");
As i feel #damian should worked but you can also tried my code I used it so mny times
Use this code:
WebElement element = driver.findElement(By.xpath("Value"));
((JavascriptExecutor)driver).executeScript(“arguments[0].scrollIntoView();”, element);
element.click();
Try:
targetElement = driver.findElement(By.xpath("your xpath"));
JavascriptExecutor js = ((JavascriptExecutor) driver);
// This:
js.executeScript("arguments[0].scrollIntoView(true);", targetElement);
targetElement.click();
// Or maybe even just:
js.executeScript("arguments[0].click();", targetElement);
You can try this way:--
JavascriptExecutor js = ((JavascriptExecutor) driver);
//Scroll your page to down using below code
((JavascriptExecutor)driver).executeScript(“window.scroll(100,2000)”);
// click on button
driver.findElement(By.xpath(//div[#class ='save-new'])).click()
Hope this help you :)

How to scroll down using Selenium WebDriver with Java

I want to scroll down my web page and i m using this code to scroll page but it is not working
public ViewBasketSentToMePageObject viewSlideShare() throws InterruptedException {
Thread.sleep(500l);
Actions action1 =new Actions(getDriver());
action1.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0030')).build().perform();
List<WebElement> function = getDriver().findElements(By.xpath("//a [#ng-click='onItemClick()']"));
function.get(13).findElement(By.xpath("//img [#ng-src='resources/images/slideshare-icon-small.png']")).click();
return getFactory().create(ViewBasketSentToMePageObject.class);
}
Looking for help
Try using simple java script below and you can scroll the page.
JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript("window.scrollBy(0,450)", "");
For scroll down:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(0, 250);");
or, you can do as follows:
jse.executeScript("window.scrollBy(0,250)", "");
Scroll until find the WebElement
Try this:
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", your_WebElement);
WebElement element = driver.findElement(By.xpath("//input [#id='giveid']"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element);
Use this. This will help you to scroll down at the particular element. I had tested on my website even. It is working fine.

Categories

Resources