Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a text exists on page using selenium [closed]

Tags:

If the text exists then click on xyz else click on abc.

I'm using the below if statement:

if(driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/table/tbody/tr[6]/td[2]")).isDisplayed()) {         driver.findElement(By.linkText("logout")).getAttribute("href");           } else {               driver.findElement(By.xpath("/html/body/div/div/div/a[2]")).click(); } 

Script fails with the following error message:

Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div/div/div/div/div/div/table/tbody/tr[6]/td[2]"} 
like image 352
user2090124 Avatar asked Feb 20 '13 07:02

user2090124


People also ask

How do you check if a text is present in a webpage in Selenium?

New Selenium IDE There are more than one ways to find it. We can use the getPageSource() method to fetch the full page source and then verify if the text exists there. This method returns content in the form of string. We can also check if some text exists with the help of findElements method with xpath locator.

How do you check if an element is present in Selenium?

We can verify if an element is present using Selenium. This can be determined with the help of findElements() method. It returns the list of elements matching the locator we passed as an argument to that method. In case there is no matching element, an empty list [having size = 0] will be returned.

How do I search text in Selenium?

text() and contains methods text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value. contains(): Similar to the text() method, contains() is another built-in method used to locate an element based on partial text match.


2 Answers

Try this code:

The below code used to check the text presence in the entire web page.

if(driver.getPageSource().contains("your Text")) {     //Click xyz }  else {     //Click abc } 

If you want to check the text on a particular web element

if(driver.findElement(By.id("Locator ID")).getText().equalsIgnoreCase("Yor Text")) {     //Click xyz }  else {     //Click abc } 
like image 123
Manigandan Avatar answered Sep 25 '22 02:09

Manigandan


Here we can use try ,except function using python web driver. see below the code

webtable=driver.find_element_by_xpath("xpath value") print webtable.text try:    xyz=driver.find_element_by_xpath(("xpath value")    xyz.click()  except:    abc=driver.find_element_by_xpath(("xpath value")    abc.click() 
like image 31
Kv.senthilkumar Avatar answered Sep 24 '22 02:09

Kv.senthilkumar