Join the DZone community and get the full member experience.Join For Free
It may so happen that in some real-time projects, Selenium WebDriver cannot perform an action on a particular web element. For example, since WebDriver simulates end-user interaction, it is natural that it will refuse to click on an element that is not visible to the end user (sometimes it also happens even though the web element is visible on the page). There can be several other similar reasons or scenarios.
Python Selenium WebDriver provides a built-in method:
What Are We Doing Here?
 in the
getElementsByClassName , and so on return all matching elements as an array. In our case, we need to act on the first matching element that can be accessed via
index  . If you know what you are doing, i.e., if you know the index of the element you want to operate, you can directly use the index, such as
getElementById ', you do not need to use any indexing, as it will return only one element (‘id’ should be unique).
Is this confusing? Let's break it down.
userName = driver.find_element_by_xpath("//button[@name='username']") driver.execute_script("arguments.click();", userName)
What Are We Doing Here?
Step 1: Inspect and capture the element using WebDriver-provided methods like '
userName = driver.find_element_by_xpath("//button[@name='username']")
Step 3: Call
Another issue faced more frequently is the need to scroll to the bottom of the web page. You can perform this operation in a single line of code:
userName = driver.find_element_by_xpath("//button[@name='username']") password = driver.find_element_by_xpath("//button[@name='password']") driver.execute_script("arguments.click();arguments.click();", userName, password)
In this case, usage of the order of web elements matters. Accessing
driver.execute_script("arguments.click();arguments.click();", userName, password)
How to Return Values
execute_script() method can return values.
print driver.execute_script('return document.getElementById("fsr").innerText')
What Happens When an Element Is Not Found?
Scenario 1: We're trying to read a property using '
print driver.execute_script('return document.getElementById("fsr").innerText') ' but there is no such element available in the web page. We get the following message in the exception trace:
selenium.common.exceptions.WebDriverException: Message: unknown error: Cannot read property 'innerText' of null
print driver.execute_script('document.getElementById("fsr").clic();') '. (Note the spelling mistake in the
click() method name.)
selenium.common.exceptions.WebDriverException: Message: unknown error: document.getElementById(...).clic is not a function
get elements text or attribute
find an element
do some operation on an element, like
change attributes of an element
scroll to an element or location on a web page
wait until the page is loaded
Published at DZone with permission of Arunkumar Velusamy. See the original article here.
Opinions expressed by DZone contributors are their own.