Python - Selenium - Debugging

By xngo on June 20, 2019

The most common issue when using Selenium is the inability to find the element using locators. Below are some tricks that might help you debug your Selenium script.

Check what Selenium see

The code below shows how to print the whole HTML page source.

from selenium import webdriver
 
# Create chrome driver.
driver = webdriver.Chrome()
 
# Open the webpage.
driver.get("https://openwritings.net")
 
# Print the whole webpage.
print(driver.page_source)

Print the content of element

my_element = driver.find_element_by_id("draggable")
print(my_element.text)

Get XPath using Inspect tool

You can use the inspect tool of Google Chrome or Firefox to copy the XPath. Here is a video showing you how to do it.

Video showing how to get XPath of element

Is your webpage using iframe?

Another reason why Selenium can't find the element is because the element in question is within an iframe. In the case of an iframe, you need to switch to that iframe first before applying your action. See Python - Selenium - Switch to iframe.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.