package p111;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Yahoo_c {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
wi.findElement(By.xpath("//[#id='UHSearchBox']")).sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
}
Above is the code.
When i run this, execution goes until "pizza" being entered into yahoo search.Later with no error message in console execution terminates.
The error image is
Please help resolve this issue.Am trying to select pizza delivery from list.
You can try Name instead of path as the yahoo search has a name for selenium to work with. Please let know if Xpath is must for you to work then i will change my code.
public static void main(String [] arg){
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
WebElement yahooSearch= wi.findElement(By.name("p"));
yahooSearch.sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
}
Or you can use the same by ID
public static void main(String [] arg){
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
WebElement yahooSearch= wi.findElement(By.id("UHSearchBox"));
yahooSearch.sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
The option you are trying to click is a link in <a> anchor tag.. you can simply use By.linkText if you are specific on the link.
driver.findElement(By.linkText("pizza delivery")).click();
Problem is that you are sendKeys, even though the pizza is typed but the drop-down list does not appears because sendKeys is not equivalent of typing through keyboard. Work around is simple. You need to perform a keyboard action after writing "pizza".
// type pizza
wi.findElement(By.xpath("//[#id='UHSearchBox']")).sendKeys("pizza");
// now perform keyboard action (of pressing space key)
wi.findElement(By.xpath("String")).SendKeys(Keys.Space);
// now click on the pizza delivery link
wi.findElement(By.linkText("pizza delivery")).click();
Try above code in your project, after adding proper wait and with correct element locators.
Try this xpath //*[contains(text(),'pizza delivery')]
It'll work! :)
Check this in firepath and make sure you get only one node with the locator.
Related
i have a class Test1 where i use this line to click on a button:
try{
driver.findElement (By.xpath(Component._emp)).click();
System.out.println("Employment is clicked");
} catch (NoSuchElementException e17) {
System.out.println("Employment is not found [TEST FAILED]");
}
And another class named Util, in this class i copied the code above like this:
public static void click_person_employment(){
try{
driver.findElement (By.xpath(Component._emp)).click();
System.out.println("Employment is clicked");
} catch (NoSuchElementException e17) {
System.out.println("Employment is not found [TEST FAILED]");
}
}
So in my class Test1 when i call like this:
Util.click_person_employment()
it throws java.lang.Nullpointer exception
Whta is the proper way to call this method.
My goal is to reduce code in my class Test1 because i have more than 100 buttons to click.
Thank you
I would recommend creating more general methods in your Utils class, ones that you can reuse over and over.
Also, System.out.println is not recommended in code. Instead you can use a logging framework - SLF4J is a good one. If you insist on using System.out.println, you can pass on the message as well.
So I'd do something like:
private static final Logger LOGGER = Logger.getLogger([className].class.getName());
public static void clickOnElement(By by){
try {
WebElement element = driver.findElement(by).click();
} catch (NoSuchElementException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
}
and then call it in test as:
Util.clickOnElement(By.xpath(...));
If you want the test to fail when the button is not found, you can rethrow the exception in the catch block.
PS. also, explicit waiting is always preferred to Thread.sleep - avoid that one in your tests as much as possible. :)
To achieve your goal, you can follow the below way:
First return WebElement from the Util class method -
public static WebElement click_person_employment(String empPath){
WebElement elem = null;
try{
elem = driver.findElement(By.xpath(empPath));
//System.out.println("Employment is clicked");
} catch (NoSuchElementException e17) {
System.out.println("Employment is not found [TEST FAILED]");
}
return elem;
}
Then call this method from Test1 class like
String empXpathStr = Component._emp;
WebElement element = Util.click_person_employment(empXpathStr);
element.click();
//Use WebDriverWait wait functionality here [Wait until element is visible]
You can also try removing the static keyword and creating the instance of Util class in your Test1 class. Finally call the method from Test1 class using the instance object.
I have the below code where I made a simple GUI. I would like Button2 to navigate to class 'Project2', which should start another piece of code. Just to note, in its current state, 'Project2' has no GUI, though I intend to add one soon. Anyway, this 'code jump' which I used by adding: String[] args = {};
Project2.main(args);
is not working, as the IDE says 'IOException must be caught or thrown'. I know how this works, though I am not sure how to implement it in the program.
Thanks in advance!
You can try to use dynamic class loading for your program. Below you can find lambda, which calls main method from com.stackoverflow.ExternalCaller class.
If you do not like to use lambda, you can create a simple anonymous class.
button.addActionListener(s -> {
try {
Class<?> externalCaller = Class.forName("com.stackoverflow.ExternalCaller");
Method main = externalCaller.getDeclaredMethod("main", new Class[]{String[].class});
main.invoke(null, new Object[]{new String[0]});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
});
ExternalCaller class in its turn looks something like that:
package com.stackoverflow;
public class ExternalCaller {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
In result once you click on the button you will get Hello World output in console.
If you would like to work with external jars etc. please look on Process class. Quick example:
Process proc = Runtime.getRuntime().exec("java -jar External.jar");
Or even more on fork/exec. You can read From Runtime.exec() to ProcessBuilder for more details.
Hope this will help. Good luck.
In most of the IDE's, when you right-click on the Button2 in the Design(GUI) pane, you can travel through:
Events -> Actions -> actionPerformed().
And write this code in the selected method to switch classes:
this.setVisible(false); //turns off the visibility of the current class
outputClass out = new outputClass(); //creating the object of the class you want to redirect to
out.setVisible(true);//turns on the visibility of the class you want to redirect to
I am trying to take user input then stored into the variable and i want to use that input into my program .
Here is my code , code is asking for user input but not loading the URL . It is just initiating the driver. Please someone correct me .
Current behavior:
Initiating the driver (IE shows the message " This is the Initial start page for wendriver server"
Asking for prompt .I gave my input in the prompt and click OK.
thats it .. after that code is not getting executed. Please help me
enter image description here
public class app{
public static void main(String[] args) throws Throwable
{
System.setProperty("webdriver.ie.driver", "C:\\Automation\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.promptResponse=prompt('Please enter the USER ID')");
if(isAlertPresent(driver)) {
// switch to alert
Alert alert = driver.switchTo().alert();
// sleep to allow user to input text
Thread.sleep(10000);
// this doesn't seem to work
alert.accept();
String ID = (String) js.executeScript("return window.promptResponse");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("my application URL");
driver.findElement(By.name("USERID")).sendKeys("username");
driver.findElement(By.name("user_pwd")).sendKeys("mypwd");
driver.findElement(By.name("submit")).submit();
.......
......
// some more code which is doing my application fucntionality
.......
......
........
private static boolean isAlertPresent(WebDriver driver) {
try
{
driver.switchTo().alert();
return true;
} // try
catch (NoAlertPresentException Ex)
{
return false;
}
}
}
If you need to take input (ie. URL) from promp then you may use JOptionPane's showInputDialog() method from Java Swing.
Code snippet:
String URL =JOptionPane.showInputDialog(null,"Enter URL");
Try following code; it should serve your purpose:
public class app{
public static void main(String[] args) throws Throwable
{
System.setProperty("webdriver.ie.driver", "C:\\Automation\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.promptResponse=prompt('Please enter the USER ID')");
isAlertPresent(driver);
String ID = (String) js.executeScript("return window.promptResponse");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("my application URL");
driver.findElement(By.name("USERID")).sendKeys("username");
driver.findElement(By.name("user_pwd")).sendKeys("mypwd");
driver.findElement(By.name("submit")).submit();
}
private static void isAlertPresent(WebDriver driver) {
try
{
driver.switchTo().alert();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // even though not needed
isAlertPresent(driver);
} // try
catch (NoAlertPresentException Ex)
{
}
}
}
I want to sign in to http://www.timesjobs.com/. Upon signing in a pop-up appears (it is the css lightbox). Cannot find the exact xpath for the username on this sign-in box. I iterated over each and every frame and tried to use firefox generated xpath for username textbox. I got exception as:
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//html/body//input[#name='j_username']"}.
Tried below code but no luck:
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS);
driver.get("http://www.timesjobs.com");
driver.findElement(By.linkText("Sign In")).click();
Thread.sleep(10000L);
List<WebElement> frames = driver.findElements(By.tagName("iframe"));
System.out.println("Total Frames: " + frames.size());
int k =0;
while(k<=frames.size()){
try{driver.switchTo().defaultContent();
driver.switchTo().frame(k);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement we1 = driver.findElement(By.xpath("//html/body//input[#name='j_username']"));
we1.sendKeys("xyzusername#xyzcompany.com");
System.out.println("in try BLOCK:"+k);
}catch(Exception e){
e.printStackTrace();
System.out.println("in catch: "+k);
}finally{
k++;}
}
System.out.println("end of the program");
}
Try the following code. It works.
Your username Field is contained within GB_Frame which is contained under GB_Frame1. So we have to switch to GB_Frame1 and then to GB_Frame. Username field has a name, so better use it over xpath.
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.timesjobs.com");
driver.findElement(By.linkText("Sign In")).click();
Thread.sleep(10000);
driver.switchTo().frame("GB_frame1");
driver.switchTo().frame("GB_frame");
WebElement we1 = driver.findElement(By.name("j_username"));
we1.sendKeys("xyzusername#xyzcompany.com");
}
I dont understand what difficulty you had in identifying the frames. It was pretty clear from the page source. Let me know if this helps you.
Seems I'm not enough smart to figure it out by myself - I have Eclipse Kepler installed, with jUnit 4.11, selenium-java 2.41 and a mozilla plugin for selenium.
Everything is great, everything (at this moment) works great.
My aim is to create a test, that repeats n times, everytime using the second String[] array element. For example:
`#Test
public void testGoogleSearch() throws Exception {
driver.get(baseUrl);
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("Find me"); // Input text from String array here
driver.findElement(By.id("gbqfb")).click();
try {
assertEquals("Find me", driver.findElement(By.id("gbqfq")).getAttribute("value"));
} catch (Error e) {
verificationErrors.append(e.toString());
}
}`
As you can see, there is static "Find me" text. I want, that my test will run 5 times, each time input changes to early defined array elements.
How can i do that? Any clues? I've read about parametrized testing, but does it really is that i need? I didn't found anything there about multiple repeating.
Any help would be great. Thank you.
I've read about parametrized testing, but does it really is that i
need?
Yes, it is exactly what you need. Parameterized.class:
#RunWith(Parameterized.class)
public class GoogleSearchClass {
private String searchString;
private String expectedString;
public GoogleSearchClass (String srch, String expect){
searchString = srch;
expectedString = expect;
}
#Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"search1", "expected1"}, {"search2", "expected2"}, {"search3", "expected3"}
});
}
#Test
public void testGoogleSearch() throws Exception {
driver.get("http://google.com");
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys(searchString); // Input text from String array here
driver.findElement(By.id("gbqfb")).click();
try {
// Assert.assertEquals(expectedString, driver.findElement(By.id("gbqfq")).getAttribute("value"));
} catch (AssertionError e) {
}
}
}