DEV Community

Tony Colston
Tony Colston

Posted on

how to interact with a webpage with Selenium and Python

Once you have navigated to a page, in order for your tests to be useful you will need to interact with that page.

In my example I am going to first find a text box and type something in the text box using Selenium.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = None
try:
    cpath = "e:\\projects\\sel\\chromedriver.exe"
    driver = webdriver.Chrome(cpath)
    driver.get("https://google.com") # note 1
    e = driver.find_element_by_name("q") # note 2
    e.send_keys("selenium") # note 3
    e.send_keys(Keys.RETURN) # note 3a
    time.sleep(3)
    driver.save_screenshot("google_selenium.png")
finally:
    if driver is not None:
        driver.close()
Enter fullscreen mode Exit fullscreen mode

Note 1 - This line causes the browser to navigate to google.com

Note 2 - In order to interact with anything on a web page you must first locate the element. As a human we do this without thinking about it. But for Selenium you must explicitly explain it. *Find an element on this page that has a name of "q".

Note 3 and Note 3a - Once you have found an element the method send_keys will send text to that web element. In the example above I sent the word "selenium" (without the quotes) followed by a RETURN key.

The RETURN key code looks a little weird. The reason we use the Selenium provided Keys object is because typing a RETURN character is platform dependent. So to make it more uniform Selenium has provided a constant that should work across platforms.

Again at the end of the program a time.sleep is used to pause the test so you can observe it. Also I take a screenshot of the test so you can look at it later.

I will have other posts that go into more detail on locators.

Top comments (0)