Find Element and Find Elements in Selenium Webdriver
To automate a web application using Selenium WebDriver, we need to
locate the elements on a web page. We use different locators to uniquely identify a web element within the web page such as
ID, Name, Class Name, Link Text, Partial Link Text, Tag Name and XPATH. In
Selenium we have two methods to find an element/elements on web page.
1) Find_Element
2) Find_Elements
Find_Element() :This method is used to find single web element on web page. If it
finds more that one similar elements on web page, it returns the first matching
element.It will throw an NoSuchElementException
exception when there is no element to find on web page.
Scenario :
Enter UserName and
Password
Click on the Login
button.
Verify the Window Title
Close the browser
Script:
from selenium
import webdriver
from selenium.webdriver.common.by import By
chromePath="C:\\BrowserDrivers\\chromedriver.exe"
driver=webdriver.Chrome(executable_path=chromePath)
driver.get("http://newtours.demoaut.com")
driver.find_element_by_name("userName").send_keys("hello")
driver.find_element(By.NAME,"password").send_keys("hello")
driver.find_element_by_name("login").click()
print(driver.title)
driver.close()
from selenium.webdriver.common.by import By
chromePath="C:\\BrowserDrivers\\chromedriver.exe"
driver=webdriver.Chrome(executable_path=chromePath)
driver.get("http://newtours.demoaut.com")
driver.find_element_by_name("userName").send_keys("hello")
driver.find_element(By.NAME,"password").send_keys("hello")
driver.find_element_by_name("login").click()
print(driver.title)
driver.close()
Find_Elements(): Find Elements method returns a list of similar web elements. It
returns an empty list if there are no elements found on web page and also it
does not throw NoSuchElementException
Scenario:
Find No of Links and Print the Text of the Links on Web Page
Script:
from selenium
import webdriver
from selenium.webdriver.common.by import By
chromePath="C:\\BrowserDriver\\chromedriver.exe"
driver=webdriver.Chrome(executable_path=chromePath)
driver.get("http://newtours.demoaut.com")
from selenium.webdriver.common.by import By
chromePath="C:\\BrowserDriver\\chromedriver.exe"
driver=webdriver.Chrome(executable_path=chromePath)
driver.get("http://newtours.demoaut.com")
List=[]
List=driver.find_elements_by_xpath("//a")
print(“No
of Links On WebPage is “,len(List))
for Eleobj in List:
print(“Link Test is “,Eleobj.text)
print(“Link Test is “,Eleobj.text)
Comments
Post a Comment