Find text with Selenium in Chrome - selenium

How can I get the text 200 in this case:
<p style="margin:0">
You can get <big class="tooltip">200</big> more</p>
I'm trying using:
ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.XPath("//*[contains(#class, 'tooltip')]"));
But can not get the text because the .Text property returns an empty string :(
Any thoughts?

You are using ClassName() with Xpath
ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.Xpath("//*[#class=\"tooltip\"]/big"));
However, I would use CssSelector in this case since css is always preferred over xpath
ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.CssSelector("big.tooltip"));
Considering the element is not inside any iframe since it is not throwing any error, I am assuming the wait is needed. Try the following
By byCss = By.CssSelector("big.tooltip");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(byCss);
});
var text = myDynamicElement.Text;
Looks the element is hidden. So JavaScript is probably your best try.
var text = ((IJavaScriptExecutor)driver).ExecuteScript("return document.querySelector('.tooltip_health_limit').innerHTML;") as string;

To get the text after you find the element:
string text = currentElement.Text;

Related

Getting value from tooltip when hover on svg element on the graph created with highcharts

I want to get text/value from the tooltip which appears when hover on svg element on the graph created with highcharts.
Below is the snippet:
Tried below code:
List<WebElement> Volumelist=driver.findElements(By.xpath("//*[name()='svg']//*[name()='g'][5]//*[name()='g'][2]//*[name()='path']"));
System.out.println("Got the list!");
new Actions(driver).moveToElement(Volumelist.get(1)).clickAndHold().build().perform();
WebElement toolTip=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#class='highcharts-halo highcharts-color-3'][#visibility='visible']")));
System.out.println("toolTip text= "+toolTip.getText());
First hover on the element on which tooltip appears and then execute :
String tooltipText = driver.findElement(By.cssSelector("g.highcharts-tooltip text tspan")).getAttribute("textContent");
You can ping me at sandpdangi13#gmail.com if that does not work for you.
Try to hover to tooltip element using this method if normal Actions hover is not working :
public static void mouseHoverJScript(WebDriver driver, WebElement element) {
String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false);"
+ " arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
((JavascriptExecutor) driver).executeScript(mouseOverScript,
element);
I found over their examples page the values with this XPath:
driver.findElement(By.xpath(.//*[name()="g" and contains(#class,"highcharts-label")]//*[name()="tspan" and #style='font-weight:bold'])).getText();
The first step is move the mouse over one point, for example with this XPath, move to the first point:
WebElement elem = DriverUtils.driver.findElement(By.xpath(.//*[name()='path' and contains(#class, 'highcharts-point highcharts-color')][1]));
new Actions(driver).moveToElement(elem).clickAndHold().build().perform();
I used the Selenium 3.9.0, with previous 3.4.0 version doesn't work for me.
So, solution that worked for me:
WebElement elem = driver.findElement(By.xpath("//[name()='svg']//[name()='g'][5]//[name()='g'][2]//[name()='path'][1]"));
new Actions(driver).moveToElement(elem).clickAndHold().moveByOffset(1, 1).pause(1000).perform();
String text=driver.findElement(By.xpath("//[name()='svg']//[name()='g'][9]//[name()='text'][1]//[name()='tspan'][3]")).getText();

Modify innerHTML using Selenium

I have this element:
WebElement element = ...
string val = element.getAttribute("innerHTML");
All I want to do is to change this innerHTML on my web page.
Is it possible?
Try this:
WebElement element = ...
((JavascriptExecutor)driver).executeScript(
"var ele=arguments[0]; ele.innerHTML = 'my new content';", element);
Selenium WebDriver does not have any direct methods to do so to change the DOM itself. However we can use JavascriptExecutor to use javascript to modify the DOM.
check this example to change the background color. You will get an idea to change the innerHTML as well.
in python use this :
element = driver.find_element_by_id("some_id")
driver.execute_script("arguments[0].innerText = 'what_you_want_to_show'", element)

Element not found - Selenium

I have written a piece of code to login into an application which is working fine. Now I have to click an add button, and I have tried it by Id, XPath, ClassName but it just gives me the exception of element not found. I thought I should apply an explicit wait, but it also did not work. Please check my code below:
public static void Login()
{
Browser.Url = "http://example.com";
_username = Browser.FindElement(By.Id("UserName"));
var password = Browser.FindElement(By.Id("Password"));
var loginbtn = Browser.FindElement(By.ClassName("btn-primary"));
_username.SendKeys("admin");
password.SendKeys("123");
loginbtn.Click();
var supplierTab = Browser.FindElement(By.Id("mainSupplier"));
supplierTab.Click();
WebDriverWait wait = new WebDriverWait(Browser, TimeSpan.FromSeconds(20));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
try
{
return d.FindElement(By.Id("btnAddSupplier_SupplierForm"));
}
catch
{
return null;
}
});
var addbtn = Browser.FindElement(By.Id("btnAddSupplier_SupplierForm"));
addbtn.Click();
}
This always gives an exception on the second last line of code that element not found.
Here is the HTML:
Try the following
public static void Login()
{
Browser.Url = "http://example.com";
_username = Browser.FindElement(By.Id("UserName"));
var password = Browser.FindElement(By.Id("Password"));
var loginbtn = Browser.FindElement(By.ClassName("btn-primary"));
_username.SendKeys("admin");
password.SendKeys("123");
loginbtn.Click();
//I think you have mentioned the iframe exist and assuming the element is inside the iframe do the following. If not skip the SwitchTo() part
//you can use name, css to identify the iframe
Browser.SwitchTo().Frame(Browser.FindElement(By.XPath("xpath for the iframe")));
var supplierTab = Browser.FindElement(By.Id("mainSupplier"));
supplierTab.Click();
WebDriverWait wait = new WebDriverWait(Browser, TimeSpan.FromSeconds(20));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.Id("btnAddSupplier_SupplierForm"));
});
//if you think the id is not unique try using xpath or css
//even though you added an explicit wait you never used it
myDynamicElement.Click();
}
Sometimes the element will be existing in the source code but will not be visible for selenium to perform a click operation. Try the below code which will wait until the element is visible:
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(20));
IWebElement element = wait.Until(
ExpectedConditions.ElementIsVisible(By.Id("btnAddSupplier_SupplierForm")));
element.Click();
Not sure if this would help, but try calling this function before you click on Add button:
void waitForPageLoad(WebDriver driver)
{
ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
wait.until(pageLoadCondition);
}
A NoSuchElementException is thrown when the locating mechanism used is not available in the dom.
A TimeoutException is thrown when your expected condition fails to be true within the time limit. An expected condition can be anything, (exists,visibility,attribute value etc...).
First you want to figure out if the element's locating mechanism you are using is indeed not found in the dom. Here is a good way to manually find out.
Open chrome and navigate to the page.
Open chrome dev tools and click on the console tab.
In the text box type $x("//*[#id='btnAddSupplier_SupplierForm']") and hit enter. This will run an xpath query, basically you are looking for any element that has an id attribute with value "btnAddSupplier_SupplierForm".
If an element appears in the console and is the correct element then it's likely that you are trying to find an element in the dom before the dom is finished loading. If no element appears in the console then you have a bad locator.
Please report your findings.

How to grab just element id - using Selenium WebDriver 2

EDIT:
I also tried this
var webElements1 = (Driver.FindElements(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Control1_lstCategory']//input"))).ToList();
I get the empty Text
I am trying to find a way to grab just ID from the list i am getting and below is my code and a print shot of my screen.
//WebDriver getting a list of Text
the below code returns me the correct number of records but it just give me the Text but I am after Text and Id of an particular Text
I tried this:
var webElements1 = (Driver.FindElements(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Control1_lstCategory']/tbody/tr/td/span"))).ToList();
this
var webElements2 = (Driver.FindElements(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Control1_lstCategory']/tbody/tr/td"))).ToList();
and this...
var webElements3 = (Driver.FindElements(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Control1_lstCategory']"))).ToList();
the all code of line gives me the correct returns but without Id.
Here is the print screen of my page:
After getting all the elements using below method, run in loop to get all element's ids:
List<WebElement> element = driver.findElements(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Control1_lstCategory']//input")));
for(WebElement ele:elements)
{
ele.getAttribute("id"); // for getting id of each element
ele.getText(); //for getting text of each element
}
1) i'll try to share the idea of the approach I would choose to resolve your issue:
getElementsByTagName('input');//returns array of elements
2) using js executor get element's attribute , ID in particular, iterating through the whole array returned by getElementsByTagName('input') and getting theirs IDs.
//sample of code I used to find color attribute:
public String jsGetColor(String cssSelector){
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x=$(\'"+css+"\');");
stringBuilder.append("return x.css('color')");
String res= (String) js.executeScript(stringBuilder.toString());
return res;
}
this is simply my assumtion how it be possible to try. hope it somehow helps you)
If you only need one id:
String id = driver.findElement(By.xpath("//*[contains(text(), 'Your text')]")).getAttribute("id");

How do you click on a checkbox from a list of checkboxes via Selenium/Webdriver in Java?

I'm using Selenium 2 (Webdriver) for automating tests on a webpage. However I wonder if there is way to check checkbox from the list of checkboxes using webdriver framework?
I tried this code but no avail:
IWebElement box = ffDriver.FindElement(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Adde_div']"));
List<IWebElement> chkbox = box.FindElements(By.TagName("input"));
ffDriver.FindElement(By.Id("ctl00_ContentPlaceHolder1_Add_lstCategory_0"));
//chkbox.g(2).click();
If you already know the id of the checkbox, you can use this method to click select it:
string checkboxXPath = "//input[contains(#id, 'lstCategory_0')]"
IWebElement elementToClick = driver.FindElement(By.XPath(checkboxXPath));
elementToClick.Click();
Assuming that you have several checkboxes on the page with similar ids, you may need to change 'lstCategory_0' to something more specific.
This is written in C#, but it shouldn't be difficult to adapt to other languages. Also, if you edit your post with some more information, I can fine-tune this example better.
Let me know if this works!
I've visited the site and successfully interacted with the checkboxes in the dropdown widget using this code:
/** Set XPath Variables **/
string dropdownWidgetXPath = "//span[contains(#id, 'selInd')]";
string checkboxXPath = "//input[contains(#id, 'selInd')]";
/** Navigate to the page **/
driver.Navigate().GoToUrl("http://www.jobserve.com/us/en/Job-Search/");
/** Click the dropdown widget **/
IWebElement dropdownWidgetElement = driver.FindElement(By.XPath(dropdownWidgetXPath));
dropdownWidgetElement.Click();
/** Identify all checkboxes present **/
var allCheckboxes = driver.FindElements(By.XPath(checkboxXPath));
/** Click each checkbox and wait so that results are visible **/
foreach(IWebElement checkbox in allCheckboxes)
{
checkbox.Click();
System.Threading.Thread.Sleep(500);
}
In Selenium webdriver you can do it like this :
All the check-boxes must be having some unique identifier then you can simply find it out by Id If they dont have a unique id (This is what I encountered while testing a web application) then it must be having some title and name attribute (or some other attribute).
Then you can try this :
driver = new FirefoxDriver();
driver.findElement(By.xpath("//input[#name='mycheckboxgroup' and #title='movies']")).click();
driver.findElement(By.xpath("//input[#name='mycheckboxgroup' and #title='songs']")).click();
By id of the checkbox you could use following code:
IWebElement elementToClick = driver.FindElement(By.ID(ctl00_ContentPlaceHolder1_Add_lstCategory_0));
elementToClick.Click();
If you don't know id then use below code by xpath:
String checkbox = "//input[#type='checkbox']"
IWebElement elementToClick = driver.FindElement(By.XPath(checkbox ));
elementToClick.Click();
The code in selenium is simple:
new WebDriverWait(driver, TimeSpan.FromSeconds(timeToHoldOn)).Until(ExpectedConditions.ElementExists((By.ClassName("ckb"))));
IWebElement dropdownWidgetElement = driver.FindElement(By.ClassName("ckb"));
dropdownWidgetElement.Click();
Thread.Sleep(1000);
var allCheckboxes = driver.FindElements(By.ClassName("ckb"));
foreach (IWebElement checkbox in allCheckboxes) {
checkbox.Click();
System.Threading.Thread.Sleep(250);
}
This is how I check and uncheck all my boxes, it has to have an Id or class.
Id example:
driver.FindElement(By.Id("someid")).click();
ClassName examaple:
driver.FindElement(By.ClassName("someid")).click();
Its short, its sweet and more importantly it works.
Try using this piece of code written in java
String checkboxes = "//*[#type='checkbox']";
List<WebElement> elementToClick = driver.findElements(By.xpath(checkboxes));
for (WebElement AllCheck : elementToClick) {
AllCheck.click();
}
Java, Clicking on multiple checkboxes at a time using the loop.
**Sample Xpath :**
CheckBox1 Xpath : //input[#class='mycheck' and #id='1']
CheckBox2 Xpath : //input[#class='mycheck' and #id='2']
Get all the elements checkbox using findelements:
List WebElement ele =
driver.findElements(By.xpath("//input[#class='mycheck']"));
Make the Xpath as string by leaving the ID and assign the ID as i.
for(int i=1; i<=ele.size(); i++) { driver.findElement(By.xpath("//input[#class='mycheck' and #id='" + + i + "']")).click(); }
i gets the value for every loop and the xpath matches the checkbox and click's it.
You can select each of the radio buttons/checkboxes by selecting the element which contains them and iterating through each one just like an array.
For example, here a ul element contains some radio buttons. I select the ul element first, then I can select each radio by using the correct index (inside the [])
//Select the ul containing the radio buttons I want to click/select
var ul = driver.FindElement(By.Id("ul_containing_radio_buttons"));
//use forloop to click each button in turn
for (var i = 2; i <= 0; i--)
{
var button= ul.FindElements(By.TagName("input"))[i];
//i is the index of the radio button in out ul element
button.Click();
}