selenium find elements code example

Example 1: find element vs find elements

Differences between findElement and findElementS method?
    --> findElement():
     
      -It does returns SINGLE web element.
      - Return type: WebElement
      - If it cannot find a web element, it throw - NoSuchElementException
          
   
   --> findElements():
      - Returns a List of WebElements
      - Return type: List<WebElement>

Example 2: selenium finding elements

from selenium import webdriver

chrome_driver_path = 'C:\Development\chromedriver.exe'
driver = webdriver.Chrome(executable_path=chrome_driver_path)

driver.get('https://www.python.org')

name = driver.find_element_by_name('q')
print(name.get_attribute('placeholder'))

python_logo = driver.find_element_by_class_name('python-logo')
print(python_logo.size)

documentation_link = driver.find_element_by_css_selector('.documentation-widget a')
print(documentation_link.text)

anchor_xpath = driver.find_element_by_xpath('//*[@id="search"]/div[2]/div[6]/div[1]/div/div'))
print(anchor_xpath.text)
# you can get xpath by right click and inspect > right click on element > 
#  >> copy >>> XPath

# you can also search by class selector
# id_selector = driver.find_element_by_id('#id')

driver.quit()

Example 3: driver.find_element_by_xpath

driver.find_element_by_xpath('//*[@id="emailField"]')

Example 4: find elements in selenium

#In Python

#Let's say that we want to locate the h1 tag in this HTML:
#<html>
#    <head>
#        ... some stuff
#    </head>
#    <body>
#        <h1 class="someclass" id="greatID">Super title</h1>
#    </body>
#</html>

h1 = driver.find_element_by_name('h1')
h1 = driver.find_element_by_class_name('someclass')
h1 = driver.find_element_by_xpath('//h1')
h1 = driver.find_element_by_id('greatID')

Example 5: selenium select element by id

driver.findElement(By.id("ui-datepicker-div"));

Example 6: selenium ways of finding

elementcss= driver.findElement(By.cssSelector('div.nav-search-input'))