Below is the HTML Query.
<div id="dvCount" style="">
<span>Total Log Count : </span>
<span id="spnLogCount">46</span>
</div>
I want to print the value 46 in Selenium WebDriver. Please let me know the code.
I am using the following code but I am unable to get the value:
WebElement Text= driver.Findelement(By.cssselector(xpath).gettext();
system.out.println("total" + Text);
But this code is not working. How do I properly get to the value in the "spnLogCount" tag?
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Users/rajnish/Desktop/my.html");
// way one
// you can create your custom x path
// one x path can be made directly using id of the span like
// xpath = //span[#id='spnLogCount']
// also not if you are not sure of the tag name then you can also use * in xpath like below
String myText = driver.findElement(By.xpath("//*[#id='dvCount']/span[2]")).getText();
System.out.println("Total Log Count : " + myText);
// way two
// you can directly use id
myText = driver.findElement(By.id("spnLogCount")).getText();
System.out.println("Total Log Count : " + myText);
// way three
// if you are using css selector then for id you can use #
myText = driver.findElement(By.cssSelector("#spnLogCount")).getText();
System.out.println("Total Log Count : " + myText);
}
UPDATE
driver.findElement(By.id("ui-id-3")).click();
driver.findElement(By.linkText("Info Log")).click();
driver.findElement(By.id("txtMessage")).sendKeys("Push Success");
driver.findElement(By.id("txtMachineName")).sendKeys("AC204");
driver.findElement(By.id("txtPortal")).sendKeys("91");
driver.findElement(By.id("btnSearch")).click();
// use it just before the sendkeys code like this
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='dvCount']/span[2]")));
String text = driver.findElement(By.xpath("//*[#id='dvCount']/span[2]")).getText();
System.out.println(text);
Hope this helps
I think you want something like this:
WebElement textElement = driver.findElement(By.xpath(".//div/span"));
String text = textElement.getText();
System.out.println("Value: " + text);
String text=driver.findElement(By.xpath("//span[#id='spnLogCount']")).getText();
System.out.println(text);
I updated you code, please use below it will work.
String Text= driver.findElement(By.cssselector("#spnLogCount")).gettext();
System.out.println("total" + Text);
As a JUnit test (and using WebDriverManager to handle the gecko driver):
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import io.github.bonigarcia.wdm.FirefoxDriverManager;
public class FirefoxTest {
private WebDriver driver;
#BeforeClass
public static void setupClass() {
FirefoxDriverManager.getInstance().setup();
}
#Before
public void setup() {
driver = new FirefoxDriver();
}
#After
public void teardown() {
if (driver != null) {
driver.quit();
}
}
#Test
public void test() {
driver.get("http://localhost:8080"); // Here your URL
WebElement webElement = driver.findElement(By.id("spnLogCount"));
System.out.println(webElement.getText());
}
}
Related
I tried the following code to enter the value BLR in a auto suggestive dropdown however although its clicking it, its now entering the text.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class testcase2 {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "//Users//suva//Downloads//chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.makemytrip.com/");
WebElement source = driver.findElement(By.id("fromCity"));
source.click();
System.out.println(source.isEnabled());
Thread.sleep(2000);
source.sendKeys("BLR");
//source.sendKeys(Keys.ARROW_DOWN);
}
}
After you click on the default 'from' selection, there is an dropdown with another input to type.
Try like this:
driver.get("https://www.makemytrip.com/");
WebElement triggerFromDropdown = driver.findElement(By.id("fromCity"));
triggerFromDropdown.click();
WebElement fromInput = driver.findElement(By.css(".autoSuggestPlugin input[placeholder='From']"));
fromInput.sendkeys('Dubai');
There can be many reasons why it is not working. It would ave been beneficial if you could provide the DOM element as well..
However a solution would be to enter text through JavaScript Executor.
The code will be something like :-
WebElement webelement = driver.FindElement(By.id("fromCity"));
JavaScriptExecutor executor = (JavaScriptExecutor)driver;
executor.ExecuteScript("arguments[0].value='" + "BLR" + "';", webelement);
For better authenticity of the above code, I need DOM. It should work though.
Below is my code, which I have written while practicing Selenium webdriver. In below code linkText is not fetching required value. Done all the things given in previous answers pertaining to same issue.
package newpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class PG9 {
public static void main(String[] args) {
System.setProperty("webdriver.ie.driver","D:\\Tools & Utilities\\IEDriverServer_x64_3.3.0\\IEDriverServer.exe");
InternetExplorerDriver driver = new InternetExplorerDriver();
String baseUrl = "http://www.monsterindia.com";
//WebDriverWait myWaitVar = new WebDriverWait(driver, 50);
driver.get(baseUrl);
//myWaitVar.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.linkText("Upload Resume")));
driver.findElement(By.linkText("Upload Resume")).click();
String expectedTitle = "Job Search | Job Vacancies | Job Opportunities in India | Monster India";
String actualTitle = "";
actualTitle = driver.getTitle();
/*
* compare the actual title of the page with the expected one and print
* the result as "Passed" or "Failed"
*/
if (actualTitle.contentEquals(expectedTitle)){
driver.findElement(By.id("name")).sendKeys("Abhay Dadhkar");
driver.findElement(By.id("mob_no")).sendKeys("9011134418");
driver.findElement(By.id("wordresume")).sendKeys("D:\\Abhay\\Abhay_Training_Profile\\Training_Profile\\AbhayDadhkar_Detail_Profile_Jan2017.docx");
} else
{
System.out.println("Test Failed");
}
driver.close();
// enter the file path onto the file-selection input field
WebElement uploadElement = driver.findElement(By.name("File name"));
uploadElement.sendKeys("D:\\Automation tools\\Selenium\\Selenium_Practice\\newhtml.html");
// check the "I accept the terms of service" check box
//driver.findElement(By.name("Open")).click();
// click the "UploadFile" button
driver.findElement(By.name("Open")).click();
}
}
By.linkText works only on <a> tags. If you want to locate by text use xpath instead
driver.findElement(By.xpath("//span[contains(., 'Upload Resume')]")).click();
You can also click the parent <div>
driver.findElement(By.className("fileUpload")).click();
I've a quick question...well what I hope will be a quick questions.
I have a div element which looks like the following:
<div class="slideshow-image" data-thumb-index="0" data-interchange="
[//someURL/5/568/1_40.jpg, (default)],
[//someURL/5/568/1_40.jpg, (small)],
[//someURL/5/568/1_70.jpg, (medium)],
[//someURL/5/568/1_base.jpg, (large)]
" data-uuid="interchange-i9a0pkp20" style="min-height: 527px; background-image: url(http://someURL/5/568/1_base.jpg);">
<div class="pageheader-overlay"></div></div>
Now through webdriver I want to get each of the URL's in the data-interchange. However I've zero idea how to get this out...can anyone out there help?
Thanks,
Phil
Here is an example based on the following conditions:
1) div will be searched by its classname
2) the result string is split into pieces by the comma
3) the split strings are checked if they end with "jpg" - if so, some formatting and trimming is made
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Selenium2Example {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
// local test URL
driver.get("http://localhost:8080");
WebElement element = driver.findElement(By.className("slideshow-image"));
String attribute = element.getAttribute("data-interchange");
String[] urls = attribute.split(",");
for (String url : urls) {
if (url.endsWith("jpg")) {
System.out.println("URL Info: " + url.replace("[", "").trim());
}
}
// Close the browser
driver.quit();
}
}
I am trying to copy the table data of the html page which is loaded on the same page after clicking on the 'Get Table' button on the previous page. However, as the page url is not changing I am getting exception of 'No such element' when trying to locate new elements on newly loaded page. Following is the code I tried:
package com.test.selenium;
import java.util.List;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import junit.framework.Test;
import junit.framework.TestSuite;
public class Example1{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\Java Stuff\\Selenium Tutorial\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.oanda.com/currency/table");
WebElement date = driver.findElement(By.name("date"));
date.sendKeys("12/04/10");
WebElement date_frmt = driver.findElement(By.name("date_fmt"));
date_frmt.sendKeys("yy/mm/dd");
WebElement curr = driver.findElement(By.name("exch"));
curr.sendKeys("US Dollar.USD");
Select sel = new Select(driver.findElement(By.name("Currency")));
sel.deselectAll();
List lsize = sel.getOptions();
int count = lsize.size();
for(int j=0;j<count;j++)
{
String lvalue = sel.getOptions().get(j).getText();
sel.selectByVisibleText(lvalue);
}
WebElement crr = driver.findElement(By.name("dest"));
crr.click();
driver.getCurrentUrl();
String table = driver.findElement(By.id("converter_table")).getText();
System.out.println(table);
}
}
According to exception it seems that element not exists on the page, or smth wrong with you xpath. Why you use xpath?! Try css selectors (they are more powerful and stable) =) e.g.
driver.findElement(By.css("#converter_table"));
P.S. if you want to verify that your selector is correct (no matter xpath or css) use dev console in browser (e.g. for css enter $("#converter_table") in console, and if element exists (and this id has no type in the name) then you'll see what this selector will return)). For xpath use $x("xpath")
UPDATE:
Simple solution i think is to add some method which will wait for element, some period of time. Below sample code in C# (test with wait method)
private IWebDriver driver;
[SetUp]
public void SetUp()
{
// Here i just create browser as you (firefox, chrome etc);
driver = CreateBrowser("http://www.oanda.com/currency/table");
}
[TearDown]
public void TearDown()
{
driver.Dispose();
}
[Test]
public void PortTest()
{
var dateElement = driver.FindElement(By.Name("date"));
dateElement.SendKeys("12/04/10");
var dateFrmt = driver.FindElement(By.Name("date_fmt"));
dateFrmt.SendKeys("yy/mm/dd");
var curr = driver.FindElement(By.Name("exch"));
curr.SendKeys("US Dollar.USD");
var crr = driver.FindElement(By.Name("dest"));
crr.Click();
WaitUntilLoad();
var table = driver.FindElement(By.Id("converter_table"));
Console.Write("the text is " + table.Text);
}
public void WaitUntilLoad()
{
int repetitionCount = 0;
bool isLoaded = false;
while (!isLoaded)
{
var table = driver.FindElements(By.Id("converter_table")).Count;
if (table > 0 )
isLoaded = true;
Thread.Sleep(250);
repetitionCount++;
Console.WriteLine("Searching again for element");
if (repetitionCount > 25) break;
}
}
you get NoSuchElement because your xpath seems wrong
try
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//*[#id='content_section']/table")));
String table = driver.findElement(By.xpath(".//*[#id='content_section']/table")).getText();
I am doing a exercise to use cssGetValue method to retrieve the value from a particular web element's CSS property.
I have 2 questions:
why the cssGetValue method returned value 13px, which web element does the method actually referenced.
1a. I want to get CSS property for section labeled as "By ID". how should I modify my code so I can get CSS property value for id="by-id" section?
I used driver.close() method, but it won't close the browser after the script finished. Please explain to me why driver.close() method didn't work in this case.
Here is my code fragment:
package wd_findElementBy;
import java.util.List;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SearchWebElements
{
WebDriver driver = new FirefoxDriver();
private String baseUrl= "http://docs.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example";
#Test
public void findElements(){
driver.get(baseUrl);
try{
List<WebElement> elements = driver.findElements(By.id("by-id"));
System.out.println("number of elements: " + elements.size());
for(WebElement ele : elements){
System.out.println(ele.getTagName());
System.out.println("get the text for web element with id='by-id' ");
System.out.println("------------------------------------------------------------");
System.out.println(ele.getText());
System.out.println("------------------------------------------------------------");
System.out.println(ele.getAttribute("id"));
System.out.println(ele.getCssValue("font-size"));
}
}
finally{
//driver.close();
driver.quit();
}
}
}
Yes, all correct.
Here's a screenshot of where to find font-size through Firebug.
Since the ids are supposed to be unique (at least for this page), you don't need findElements to find a list of elements with id by-id and loop through, instead, you use findElement to get the element directly.
try{
WebElement byId = driver.findElement(By.id("by-id"));
System.out.println(byId.getTagName());
System.out.println("get the text for web element with id='by-id' ");
System.out.println("------------------------------------------------------------");
System.out.println(byId.getText());
System.out.println("------------------------------------------------------------");
System.out.println(byId.getAttribute("id"));
System.out.println(byId.getCssValue("font-size"));
}
}
For getting CSS value:
driver.findElement(By.id("by-id")).getCssValue("font-size");//similarly you can use other CSS property such as background-color, font-family etc.
For quit/close the browser after finishing the execution of script:
driver.quit();
public class GetCssValues {
public WebDriver driver;
private By bySearchButton = By.name("btnK");
#BeforeClass
public void setUp() {
driver = new FirefoxDriver();
driver.get("http://www.google.com");
}
#Test(priority=1)
public void getCssValue_ButtonColor() {
WebElement googleSearchBtn = driver.findElement(bySearchButton);
System.out.println("Color of a button before mouse hover: " + googleSearchBtn.getCssValue("color"));
Actions action = new Actions(driver);
action.moveToElement(googleSearchBtn).perform();
System.out.println("Color of a button after mouse hover : " + googleSearchBtn.getCssValue("color"));
}
#Test(priority=2)
public void getCssValue_ButtonFontSize() {
WebElement googleSearchBtn = driver.findElement(bySearchButton);
System.out.println("Font Size of a button " + googleSearchBtn.getCssValue("font-size"));
}
#Test(priority=3)
public void getCssValue_ButtonFontWeight(){
WebElement googleSearchBtn = driver.findElement(bySearchButton);
System.out.println("Font Weight of a button " +getFontWeight(googleSearchBtn) );
}
public String getFontWeight(WebElement element) {
//Output will return as 400 for font-weight : normal, and 700 for font-weight : bold
return element.getCssValue("font-weight");
}
#AfterClass
public void tearDown() {
driver.quit();
}
}
output:
Color of a button before mouse hover: rgba(68, 68, 68, 1)
Color of a button after mouse hover : rgba(34, 34, 34, 1)
Font Size of a button 11px
Font Weight of a button 700
The value is correct. You need access computed section in dev-tools
Add the property name in the getCssValue to get the info regarding same
Some Examples are :-
System.out.println("font-size = "+ele.getCssValue("font-size"));
System.out.println("background = "+ele.getCssValue("background"));
System.out.println("line-height = "+ele.getCssValue("line-height"));
System.out.println("color = "+ele.getCssValue("color"));
System.out.println("font-family = "+ele.getCssValue("font-family"));
Refer:-