Tutorial writing Selenium test script in Python
Continuing from last tutorial, we now extend the test_chrome.py script to have Selenium point the Chrome browser to icanhazdadjoke.com website and search for “cat” jokes by typing “cat” into the field and clicking search…
This the full script …
The implicitly_wait on line 13 will give up to 10 second for the page to load; otherwise the find_element will not be able to find the DOM elements.
Line 15 finds the input field by XPATH.
Line 18 finds the search button by ID and then clicks it.
Chrome browser exits when script done. We sleep(10) to keep the browser up for 10 seconds so we can see the results.
Alternative ways to Find
In Selenium, there are many ways of finding the same thing. Instead of using find_element() with “By” argument from selenium.webdriver.common.by, we can use find_element_by_xpath() method on the driver link below…
Note that if it does not find anything, it will return None, which you can test for as shown above.
Find by CSS Selector
Next let’s use find_selector_by_css() to get the number of results that was returned by the web page…
Note how after finding the element, we use the “text” property of the element to see the HTML that is in that element.
There you have it — a Python script that open browser to a website, put in a search term, clicked a button, and retrieved the results from the webpage.