Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling to element using webdriver?

I am still learning and in response to one of my questions: here, I was told to that it might be due because the element in question is not in view.

I looked through the documentation and SO, here was the most relevant answer: here

You can use the "org.openqa.selenium.interactions.Actions" class to move to an element:

WebElement element = driver.findElement(By.id("my-id")); Actions actions = new Actions(driver); actions.moveToElement(element); ## actions.click(); actions.perform(); 

When I try to use the above to scroll to the element: It says WebElement not defined.

I think this is because I have not imported the relevant module. Can someone point out what I am supposed to import?

Edit: As pointed out by alecxe, this was java code.

But in the meantime right after trying to figure it out for some time. I have found out the import method for WebElement:

from selenium.webdriver.remote.webelement import WebElement 

Might help someone like me.

The how of it is also a good lesson, IMO:

Went to: Documentation The

class selenium.webdriver.remote.webelement.WebElement(parent, id_, w3c=False) 

Need to be separated into the command form mentioned above.

like image 615
Sid Avatar asked Jan 19 '17 14:01

Sid


People also ask

How do I scroll up page in Selenium WebDriver?

Hence, to scroll up or down with Selenium, a JavaScriptExecutor is a must. The scrollBy() method involves two parameters, x, and y, that represent the horizontal and vertical pixel values, respectively.


1 Answers

You are trying to run Java code with Python. In Python/Selenium, the org.openqa.selenium.interactions.Actions are reflected in ActionChains class:

from selenium.webdriver.common.action_chains import ActionChains  element = driver.find_element_by_id("my-id")  actions = ActionChains(driver) actions.move_to_element(element).perform() 

Or, you can also "scroll into view" via scrollIntoView():

driver.execute_script("arguments[0].scrollIntoView();", element) 

If you are interested in the differences:

  • scrollIntoView vs moveToElement
like image 141
alecxe Avatar answered Sep 25 '22 14:09

alecxe