Rules for id attribute:
Ways to locate HTML elements on a web page:
Order of preference:
How to locate HTML elements by name attribute:
How to locate HTML elements by id attribute:
-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:
-Selenium WebDriver method, ex:
browser=webdriver.Firefox()
browser.get(“https://stackoverflow.com”)
element = browser.find_element(By.CLASS, “vector-menu-heading”)
The name attribute:
- is mostly used in forms to reference the element when data is submitted, e.g. login forms
XPath
Absolute XPath
Relative XPath
- 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
XPath Syntax: nodename
Selects all nodes with the name “nodename”
Class names
not unique
What are waits?
Explicit Waits
- It’s good practice to use explicit waits before locating and interacting with elements
Implicit Waits
CSS Selectors: *
Universal selector: selects all elements. Optionally, it may be restricted to a specific namespace or to all namespaces
CSS Selectors: elementname
Type selector: selects all elements that have the given node name.
Example: input will match any element with the name elementname
CSS Selectors: .
Class selector: selects all elements that have the given class attribute. Example: .index will match any element that has a class of "index".
CSS Selectors: #
id selector: selects an element based on the value of its id attribute. There should be only one element with a given ID in a document.
Example: #toc will match the element that has the ID “toc”.