Selenium WebDriver Finding Element by Partial Class Name - java

In the frame I'm working with, I have the following element:
<div class="x-grid3-cell-inner x-grid3-col-expRepCol"> New session from client IP 192.168.5.3 (ST=/CC=/C=) at VIP 192.168.5.2 Listener /Common/Tomcat (Reputation=Unknown)</div>
As well as many other similar elements. I am trying to locate this element by partial name text and click it with the following code:
String expectedText = "New session from client IP";
driver.findElement(By.className("div[class*='"+expectedText+"']")).click();
And I have also tried with cssSelector:
String expectedText = "New session from client IP";
driver.findElement(By.cssSelector("div[class*='"+expectedText+"']")).click();
But WebDriver keeps throwing an exception stating it's unable to locate that element. Any suggestions as to what could be the problem?

<div class="dd algo algo-sr Sr" data-937="5d1abd07c5a33">
<div class="dd algo algo-sr fst Sr" data-0ab="5d1abd837d907">
Above 2 are the HTML elements in yahoo search results. So if we wanna get these elements using partial class name with selenium python, here is the solution.
driver.find_element_by_css_selector("div[class^='dd algo algo-sr']")
In the same way we can get any elements with partial match on any attribute values like class name, id etc.
find elements with css selector partial match on attribute values

By.className is looking for a class with the name entered.
By.cssSelector is looking for a match for the selector you entered.
What you're attempting is to match the text of the div against class, which won't work.
You can try something like this:
driver.findElement(By.xpath("//div[contains(text(),'"+expectedText+"')]")).click();

I believe this will work:
driver.findElement(By.className("x-grid3-cell-inner x-grid3-col-expRepCol").click();

Related

Unable to get the text from div class - selenium java

<div class="jss7113 jss7118"><div></div><div class="jss7114">Invalid username or password</div><button class="MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-textPrimary" tabindex="0" type="button"><span class="MuiButton-label"><i icon="close-circle-outline" title="" class="mdi mdi-close-circle-outline" aria-hidden="true"></i></span><span class="MuiTouchRipple-root"></span></button></div>
This is what wrote
//System.out.println(driver.findElement(By.cssSelector("*.jss5107")).getText()); //Get the error message from the Invalid credentials
//System.out.println(driver.findElement(By.cssSelector("div[class = 'jss7114']")).getText().equals("Invalid username or password"));
//System.out.println(driver.findElement(By.xpath("//div[#class = 'jss7114']")).getText().equals("Invalid username or password"));
It seems like the class name you're trying to find doesn't exist:
//System.out.println(driver.findElement(By.cssSelector("*.jss5107")).getText());
this type of gibberish names for elements usually indicates random attribute values being generated and making your automation relying on those values is a no go because we want our automation to be as solid and low maintenance as possible.
Instead, try to find a better way to locate the element you're looking for.
I could've tried to give you a better locator but it seems like you pasted a part of the HTML code which I can't read it properly (for example there's a div tag that immediately gets closed right after):
<div class="jss7113 jss7118"><div></div>
Please provide a better snippet of this part of the HTML in order for us to help with your question.
If you want to validate the message, you can locate the element by the text within it:
driver.findElement(By.xpath("//div[contains(text(),'Invalid username or password')]

accessing the class name Selenium Webdriver

I am trying to access a web element in this example I am trying to access the className
driver.findElement(By.className("more-option")).click();
from bellow but it fails.
<div class="text-center">
<a class="small text-muted js-more-options" href="#">More
Options</a> = $0
</div>
My goal is to be able to test the ability to click More options button
Edit
I have tried
driver.findElement(By.cssSelector("td[title='More options']")).click();
and
driver.findElement(By.partialLinkText("options")).click();
There are to many option you can click on element.You can use contains().
Contains() is a method used in XPath expression.
driver.findElement(By.XPath("//a[contains(text(),'More Options')]")).Click();
or
driver.findElement(By.XPath("//a[contains(#class,'small')]")).Click();
if you get more than one element then you have to use index and click on particular element.
Find element using By.className just for single class name.
Try following approach.
By css selector:
driver.find_element_by_css_selector('div.text-center a.small.text-muted.js-more-options').click()
driver.find_element_by_css_selector('a[class="small text-muted js-more-options"]').click()
By xpath:
driver.find_element_by_xpath('//div[#class="text-center"]//a[#class="small text-muted js-more-options"]').click()
By partial link text:
driver.find_element_by_partial_link_text('Options').click()

Use Selenium Java to get string text from HTML

I want to get Selenium with Chromedriver to recognize and import a line of html text into a Webelement variable.
Given this HTML:
<li id="password_rules">
<strong>Password Rules</strong>
<p>The database password rules conform with...:</p>
<ul>
<li>The password can not be the same as the user id.</li>
<li>Password length must be between 8 and 25 characters.</li>
</ul>
</li>
I want to grab the text in the last list element ("Password length must be between 8 and 25 characters.").
This is the java code I'm attempting to use:
WebElement passwordCriteria = driver.findElement(By.xpath("//*[#id = 'password_rules']//*[contains(text(), 'Password length must be between ')]"));
String lineText = passwordCriteria.getText();
When that Java executes, it returns an error saying the element cannot be found:
Exception in thread "main"
org.openqa.selenium.InvalidSelectorException: invalid selector: Unable
to locate an element with the xpath expression //[contains((text(),
'Password length must be between ')] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string
'//[contains((text(), 'Password length must be between ')]' is not a
valid XPath expression.
Any insight is much appreciated.
If you are grabbing a WebElement by it's id, then you don't need your extra specific xPath. id is supposed to be unique by convention. If you have other html elements with the same id, consider changing them to a class.
You should be able to grab the element like this:
WebElement passwordCriteria = driver.findElement(By.id("password_rules"));
If you're committed to finding the element by the id containing some text then the way you should do it is as follows:
WebElement passwordCriteria = driver.findElement(By.xpath("//*[contains((text(),'Password length must be between')]"));
Also, sometimes Selenium will complain if elements are not visible on the page when you try and reference them. Sometimes you need to wait, other times you need to perform some other action to make the text visible before referencing it, like hovering the mouse over a dropdown, etc.
For example
Suppose the html you pasted here is an error message. This error message does not start out as being 'visible', but instead it is shown after the user types their password in incorrectly. In such an instance, Selenium won't let you reference the text from an element inside this div, since it's not currently view-able. Instead, what you would have to do is use Selenium to input the incorrect password in the fields, wait for the error message to be displayed, and then finally reference the WebElement, only after it is able to be seen.
EDIT:
I misread OP's intention. The element that OP is trying to reference is NOT the element with the id, but rather a child of that element. Instead of rewriting my answer, I will point out that #Grasshopper answer has both css and xPath solutions.
You can try these locators if the concerned li is always the last child.
Css - "li[id='password_rules'] > ul > li:last-child"
xpath - "//li[#id='password_rules']/ul/li[last()]"
As per your question as the desired text is within Password Rules you have to induce WebDriverWait with ExpectedConditions as textToBePresentInElementLocated and then retrieve the text as follows :
new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//li[#id='password_rules']//ul//li"), "Password length"));
String lineText = driver.findElement(By.xpath("//li[#id='password_rules']//ul//li[contains(.,'Password length')]")).getAttribute("innerHTML");
Thank you for the help everyone. I finally got it using the following:
new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//li[#id = 'password_rules']"), "Password length must be between "));
WebElement passwordCriteria = driver.findElement(By.xpath("//li[#id = 'password_rules']/ul/li[2]);
String lineText = passwordCriteria.getText();
Your original example had // which should only be used at the beginning of an xpath.

Selenium WebDriver Java locating an element with dynamic ID

I'm currently having troubles on locating this element with dynamic id. Here are the screenshots below.
What i have right now is the element of Variables (8) //a[contains(.,'Variables (8)')]. What i need is only the "Variables" since the number 8 is always changing.
Any thoughts on this? Any ideas will be much appreciated. Thanks
First of all 'Variables (8)' is not Id, its text. Id's are not dynamic since they represent unique identifier for the web element. This will look like this (based on your example):
<div class="field" id="fieldId">
As for your question, you can find the element by partial linked text:
driver.findElement(By.partialLinkText("Variables"));
This will give you the a element no meter what the number is.
You can try the below:
driver.findElement(By.cssSelector("a:contains('Variables')"));
If you want the word "Variables" , use the below:
String str = driver.findElement(By.cssSelector("a:contains('Variables')")).getText().split(" ")[0];
Hope this Helps....
What I understand from your question is you want to locate the <a> tag which contains text "Variables".
Try using this xpath:
//div[#class="field"]/a[contains(.,"Variables")]
This xpath will locate the <a> tag after the div tag with class name =field and Contains method with <a> tag will find the element which contains text "Variables"
try this:
String varText = driver.findElement(By.cssSelector("div.triggerFirst>div:nth-child(1)>a")).getText();

How to access dynamic text within HTML icon tag with selenium WebDriver?

<span class="class name">16</span>
The "16" is dynamic and I don't know how to access it using Selenium Webdriver in java. I've tried By.xpath() and it didn't work but I feel like cssSelector would be more robust in this situation. could someone tell me how to access the 16. I'm writing a method to check the expected value to the given value. The 16 is part of an icon. I don't think that will make a difference because the cssSelector should still do the job.
You would do something like:
WebDriver driver = new FirefoxDriver();
String content = driver.find_element_by_class_name("class name").getText();
If there are multiple elements with the same class name you can use find_elements_by_class_name and iterate through them.
You could add a "data-" tag to the span element: example <span class="class name" data-hook="some.element.number">16</span>
Then your locator would look like this --> driver.findElement(By.cssSelector("[data-hook='some.element.number']");

Categories

Resources