Ciaran
Ciaran

Reputation: 478

Interacting with websites using selenium

I am trying to interact with websites using the package "selenium". I have a problem understanding what this line is doing:

elem = driver.find_element_by_name("q")

The line before that checks that the site contains the word "python" in the title. Then this line somehow finds the search text box on the webpage with the letter "q". The package documentation jumped over this point, what am I missing?

Full code:

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get("http://www.python.org")
        self.assertIn("Python", driver.title)
        elem = driver.find_element_by_name("q")
        elem.send_keys("pycon")
        assert "No results found." not in driver.page_source
        elem.send_keys(Keys.RETURN)

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()

So far I can see that I can find certain elements using:

find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector

But why does "q" specifically point to the search box on the python website?

Upvotes: 0

Views: 2365

Answers (1)

Louis
Louis

Reputation: 151370

If I go into the debugger to inspect the element that serves as the search box at the top of the www.python.org page, this is what I see:

<input id="id-search-field" name="q" role="textbox" class="search-field placeholder" placeholder="Search" tabindex="1" type="search">

Note the attribute name="q". This element is named q so driver.find_element_by_name("q") finds it.

Upvotes: 1

Related Questions