-2

How do I scroll to a specific element and click on it?

Below is the code which I have tried:

Random R = new java.util.Random();
List<WebElement> Top_Stores =driver.findElements(By.xpath(".//*[@id='go_body']/main/section/div/div[2]/div/div/div[2]/aside/div[1]/section[1]/a"));
WebElement randomElement = Top_Stores.get(R.nextInt(Top_Stores.size()));
String S=randomElement.getText();
System.out.println(S);
Actions actions = new Actions(driver);
actions.moveToElement(randomElement);
actions.perform();
randomElement.click();
  • What's not working? And why do you want to scroll before you click the element? – GalAbra Jan 25 '18 at 09:55
  • @GalAbra While i am trying to click on element my script is not able to locate it as the element is at the bottom of the screen, So that i am trying to scroll to element location and click on it... – Narendra Chetan Jan 25 '18 at 09:59
  • Below is the error i am getting: org.openqa.selenium.WebDriverException: Element is not clickable at point (422.66668701171875, 0.399993896484375). Other element would receive the click: Command duration or timeout: 390 milliseconds – Narendra Chetan Jan 25 '18 at 10:01
  • Your question heading `How to scroll to a specific element and click on it?` doesn't matches with the error you are seeing `WebDriverException: Element is not clickable at point`which is a possible duplicate of [Selenium Web Driver & Java. Element is not clickable at point (36, 72). Other element would receive the click:](https://stackoverflow.com/questions/44912203/selenium-web-driver-java-element-is-not-clickable-at-point-36-72-other-el) – undetected Selenium Jan 25 '18 at 10:36
  • @Debanjan if that is the case can u please help me out of this situation by clicking on the element – Narendra Chetan Jan 25 '18 at 10:40
  • @NarendraChetan Edit your question heading to depict your actual problem and follow the link to solve your issue. – undetected Selenium Jan 25 '18 at 10:44
  • I simply searched on google "How to scroll in selenium" [this(click here)](https://stackoverflow.com/questions/12293158/page-scroll-up-or-down-in-selenium-webdriver-selenium-2-using-java) is what is got. wasn't that difficult. – Alok Jan 25 '18 at 11:14
  • Java + Selenium scrolls for you when you attempt a click. You don't need to scroll to the element yourself. – JeffC Jan 25 '18 at 14:53

1 Answers1

1

You can scroll with javascript:

public void scrollToElement(WebElement element) {
    ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
}
Fenio
  • 3,528
  • 1
  • 13
  • 27