Linktext is not working - java

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();

Related

Although the text is present in the pagesource() when I execute pageSource().contains.(text), it returns false

I am trying to find the subheading text: "You can join this team without approval if you have a farzanshaikh.com email address."
Although this text is present in the page source, it always returns false for .contains()
Code:
package JUnitTesting;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestOne {
WebDriver driver;
String BaseUrl;
String TeamDomain = "farzanshaikh.com";
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Automation\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
BaseUrl = "http://farzanshaikh.flock.co/";
driver.get(BaseUrl);
driver.manage().window().maximize();
}
#Test
public void test() {
String element = driver.getPageSource();
System.out.println(element);
if(driver.getPageSource().contains("You can join this team without approval if you have a "+TeamDomain+" email address.")){
System.out.println("The Sub Heading on the Team URL page is Correct");
}
else{
System.err.println("The Sub Heading on the Team URL page is Wrong.");
}
}
#After
public void tearDown() throws Exception {
Thread.sleep(2000);
driver.quit();
}
}
Well, I don't see any issue either in your code or in the result.
Manually when we look into the webpage we can see the text You can join this team without approval if you have a farzanshaikh.com email address.
But when we try to get the pagesource the part of the string cotaining the text reads like: You can join this team without approval if you have a <span class='domains-list'>{{canJoinDomains}}</span> email address.
Finally, you are trying to use contains to validate if the first string is present in the second string. Hence it fails. If you can reduce the first string to something like You can join this team without approval, it would return True.
Let me know if this answers your question.

Eclipse - Can't see assert outcome in console

My Java is quite basic and I am very new to Selenium and I'm testing to see how it works. For some reason in my code, I can see the "assert" outcome in the console, whilst in another part I cannot. I've logged messages to the console before and after the assertation (both of which show) but the assertation result does not.
package automationFramework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.junit.Assert.*;
public class Weather {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "//home//aaronh//Documents//Drivers//geckodriver");
// System.setProperty("webdriver.gecko.driver",
// "//home//aaron//JARs//geckodriver-v0.14.0-linux64//geckodriver");
WebDriver driver = new FirefoxDriver();
// launch browser and go to the website
String url = "https://www.bbc.com/weather";
driver.get(url);
driver.manage().window().maximize();
// search weather information for Bristol
WebElement location = driver.findElement(By.name("search"));
location.clear();
location.sendKeys("Bristol, Bristol");
// click search button
WebElement search = driver.findElement(By.name("submitBtn"));
search.click();
// this assertion fails because it checks the title before the search and IS LOGGED TO THE CONSOLE
// for
// Bristol weather has finished
// String bristol = driver.getTitle();
// assertEquals("BBC Weather - Bristol", bristol);
System.out.println("before wait");
WebDriverWait wait = new WebDriverWait(driver, 5);
if (wait.until(ExpectedConditions.titleContains("BBC Weather - Bristol"))) {
String bristol = driver.getTitle();
System.out.println("before assert " + bristol);
// this does not log to the console
assertEquals("BBC Weather - Bristol", bristol);
System.out.println("after assert");
}
driver.close();
System.out.println("Test script executed successfully.");
System.exit(0);
}
}
Can someone please tell me why the assertation outputs in one place and not the other? I appreciate the getTitle is pointless because the code won't get these unless the title is what we're asserting but hey, I'm just testing it out.
Thanks.
You have to distinguish between the Console and the JUnit view itself.
Example:
#Test
public void test() {
System.out.println("1");
Assert.assertEquals("A", "A");
System.out.println("2");
Assert.assertEquals("A", "B");
System.out.println("3");
}
results in:
A) console output
1
2
B) JUnit view output
org.junit.ComparisonFailure: expected:<[A]> but was:<[B]>
at org.junit.Assert.assertEquals(Assert.java:115)
...
Long story short: works as expected; and more importantly: asserts that pass do not create any observable output!

Printing desired text using selenium webdriver

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());
}
}

how to locate an element of a page after new data loaded on the same page in selenium webdriver

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();

Selenium WebDriver - getCssValue() method

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:-

Categories