Selenium Flashcards
Rules for id attribute:
- must be unique in a HTML document
- least one character
- no spaces
- case sensitive
Ways to locate HTML elements on a web page:
Order of preference:
- id
- name (if unique)
- class
- CSS selector
- XPath without text or indexing
- Link text or partial link text
- XPath with text or indexing
How to locate HTML elements by name attribute:
- ctr + F and type in the name of the element
- Selenium WebDriver method, ex:
browser=webdriver.Firefox()
browser.get(“https://stackoverflow.com”)
element = browser.find_element(By.NAME,”q”)
How to locate HTML elements by id attribute:
- ctr + F and type in the id
-Selenium WebDriver method, ex:
browser=webdriver.Firefox()
browser.get(“https://stackoverflow.com”)
element = browser.find_element(By.ID, “hiking”)
How to locate HTML elements by class attribute:
- ctr + F and type in the class, preceded by “.”, ex: .vector-menu-heading
-Selenium WebDriver method, ex:
browser=webdriver.Firefox()
browser.get(“https://stackoverflow.com”)
element = browser.find_element(By.CLASS, “vector-menu-heading”)
The name attribute:
- does not have to be unique
- is mostly used in forms to reference the element when data is submitted, e.g. login forms
XPath
- stands for XML path language
- uses path expressions to identify and navigate nodes in an XML document
- can be used to select one or more nodes in the document using relative or absolute paths
- used in worst case scenarios, like when a specific class, name, or id is unavailable
Absolute XPath
- the complete path from the root to the desired element, ex: /html/body/form[1]
- not as desirable to use as relative XPath
Relative XPath
- just references the desired element, ex: //form[1]
- preferred over absolute XPath
How to locate HTML element by XPath:
-Selenium WebDriver method, ex:
browser=webdriver.Firefox()
browser.get(“https://stackoverflow.com”)
element = browser.find_element(By.XPATH, “//form[1]”)
XPath Syntax: //
selects nodes in the document from the current node that match the selection no matter where they are
XPath Syntax: /
Selects from the root node
XPath Syntax: .
Selects the current node
XPath Syntax: ..
Selects the parent of the current node
XPath Syntax: @
Selects attributes