Main page contains more than 300 links, clicking on each link on main page opens new window (of course) with table. I always need table value from the same position, yet... sometimes (but only sometimes) that (needed) table value is actally also a link which opens new window after clicking on it.
If clicking on that table value opens new window (with new table) I need specific table value from that new window, if not (if original table value is not a link) I need only original table value.
I tried with the code below but error occured...
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[#id='aodds-info']/div[2]/table/tbody/tr[3]/td[2]"}
Command duration or timeout: 33 milliseconds
package newpackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class newdist {
public static void main(String[] args) throws IOException, InterruptedException {
// Open main page
WebDriver driver = new FirefoxDriver();
driver.get("Main page link");
Thread.sleep(5000);
// Maximize main page window
driver.manage().window().maximize();
Thread.sleep(1000);
// List off all links on Main page
List<WebElement> lista1 = driver.findElements(By.cssSelector(".first-cell.tl>a"));
// loop trough all links on Main page
for(int j=0;j<lista1.size();j++){
WebElement link = lista1.get(j);
List<WebElement> links = driver.findElements(By.cssSelector(".first-cell.tl>a"));
String homePage = driver.getWindowHandle();
link.click();
Thread.sleep(3000);
// Window handles block
Set<String>windows=driver.getWindowHandles();
Iterator iterator = windows.iterator();
String currentWindowId;
while (iterator.hasNext()){
currentWindowId = iterator.next().toString();
if(! currentWindowId.equals(homePage)){
driver.switchTo().window(currentWindowId);
Thread.sleep(3000);
// "clicking" on specific table value (clicking maybe opens new window)
driver.findElement(By.xpath(".//*[#id='sortable-1']/tbody/tr[6]/td[1]/span")).click();
Thread.sleep(3000);
// if clicking opens new window print specific value from table in that new window
try {
String s0 = driver.findElement(By.xpath(".//*[#id='aodds-info']/div[2]/table/tbody/tr[3]/td[2]")).getText();
System.out.println(s0);
}
// if clicking doesn't open new window print current table value from current window
catch (NoSuchElementException e){
String s0 = driver.findElement(By.xpath(".//*[#id='sortable-1']/tbody/tr[6]/td[1]/span")).getText();
System.out.println(s0);
}
// return to Main page
finally{
driver.close();
driver.switchTo().window(homePage);
Thread.sleep(2000);
}
}
}
}
}
}
The NoSuchElementException is imported from java.util. To catch web elements exception you need to import from org.openqa.selenium.
As a side note, using explicit and implicit wait is much better practice then using Thread.sleep.
Related
I am currently trying to automate JMeter (as an sample application) using Marathon Java Drivers. I am able to open JMeter but when i try to right click on Test Plan under the left pane, i am not able to do so. Can you please tell me what i am doing wrong. Thanks.
package javadriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Window;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import net.sourceforge.marathon.javadriver.JavaDriver;
import net.sourceforge.marathon.javadriver.JavaProfile;
import net.sourceforge.marathon.javadriver.JavaProfile.LaunchMode;
import net.sourceforge.marathon.javadriver.JavaProfile.LaunchType;
import org.openqa.selenium.support.PageFactory;
public class JavaDriverTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_COMMAND_LINE);
profile.setLaunchType(LaunchType.SWING_APPLICATION);
profile.setMainClass("org.apache.jmeter.NewDriver");
profile.addClassPath("C:\\apache-jmeter-5.1.1\\bin\\ApacheJMeter.jar");
profile.setWorkingDirectory("C:\\\\apache-jmeter-5.1.1\\\\bin");
WebDriver driver = new JavaDriver(profile);
Window window = driver.manage().window();
window.maximize();
WebElement elementLocator = driver.findElement(By.cssSelector("label[text='Test Plan']"));
new Actions(driver).moveToElement(elementLocator, 50, 25).contextClick(elementLocator).build().perform();
//new Actions(driver).clickAndHold(elementLocator);
//new Actions(driver).contextClick(elementLocator).perform();
//driver.quit();
}
}
Looks like you are trying to get the components before the application is completely opened. So Marathon is not able to find the component.
The right click you wanted to perform is a tree item so you need to find the tree and then get node from that.
Check this link for how to locate different types of components where for Swing and JavaFX both are defined. https://marathontesting.com/marathonite-user-guide/selenium-webdriver-bindings/
Please check the following code this will give a better understanding.
package javadriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import net.sourceforge.marathon.javadriver.JavaDriver;
import net.sourceforge.marathon.javadriver.JavaProfile;
import net.sourceforge.marathon.javadriver.JavaProfile.LaunchMode;
import net.sourceforge.marathon.javadriver.JavaProfile.LaunchType;
public class JMeterTest {
private JavaDriver driver;
#BeforeTest
public void createJavaProfile_ExecJarLauncher() {
// We prefer Executable jar rather than using Java Command Line
// launcher as the application loads with a blurb and then the main
// window opens. So that we can specify the Start window from where the
// operations are performed. Other wise after creating driver you need to put sleep until the main window is opens.
JavaProfile profile = new JavaProfile(LaunchMode.EXECUTABLE_JAR);
profile.setLaunchType(LaunchType.SWING_APPLICATION);
profile.setExecutableJar("/Users/adityakarra/Projects/apache-jmeter-5.2.1/bin/ApacheJMeter.jar");
profile.setWorkingDirectory("/Users/adityakarra/Projects/apache-jmeter-5.2.1/bin");
// As the application title differs based on the Version number we have
// passed regex to match the window title.
profile.setStartWindowTitle("/^Apache JMeter.*");
driver = new JavaDriver(profile);
// Finally printing the window title after every thing is loaded.
System.out.println("Window Title ::: " + driver.getTitle());
}
#Test
public void getTreeItem() throws InterruptedException {
// As the context menu you wanted to click is a tree item. So find the
// tree initally.
WebElement tree = driver.findElementByTagName("tree");
// Now for getting the tree item we use select by properties and get the
// node.
WebElement node = tree.findElement(By.cssSelector(".::select-by-properties('{\"select\":\"/Test Plan\"}')"));
// Performing right click on the tree item
new Actions(driver).moveToElement(node, 50, 25).contextClick(node).build().perform();
// Clicking on one of the menu items in the context menu.
driver.findElementByCssSelector("menu-item[text='Disable']").click();
new Actions(driver).moveToElement(node, 50, 25).contextClick(node).build().perform();
driver.findElementByCssSelector("menu-item[text='Enable']").click();
}
#AfterTest
public void tearDown() {
if (driver != null)
driver.quit();
}
}
Note: I'm one of the contributor for Marathon.
I am trying to use phantomjs for testing, I have one login page with obvious two parameters username and password. If i try same code with google url where i have to pass only one element with and say element.submit(); but in my login page i want to pass two elements how to achieve the same ?
here is my code -
import java.io.File;
import java.io.IOException;
import org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
public class PhantomExample {
public PhantomExample() {
System.out.println("this is constructor");
}
#Test
public void verify() {
File src = new File("C:\\Users\\Admin\\Downloads\\Compressed\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
DesiredCapabilities phantomjsCap = new DesiredCapabilities();
phantomjsCap.setJavascriptEnabled(true);
phantomjsCap.setCapability("phantomjs.binary.path", src.getAbsolutePath());
System.out.println("inside the verify method");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
WebDriver driver = new PhantomJSDriver(phantomjsCap);
driver.get("http://localhost:8080/MyApp/Login");
System.out.println(driver.getPageSource());
WebElement el =driver.findElement(By.name("username"));
WebElement elp =driver.findElement(By.name("password"));
el.sendKeys("username");
elp.sendKeys("0");
el.submit();
elp.submit();
System.out.println(driver.getTitle());
System.out.println(driver.getCurrentUrl());
System.out.println(driver.getPageSource());
File Ss=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(Ss, new File("d:/sample.jpg"));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
driver.quit();
}
}
Here i created two separate elements and expecting to get the response, but when i run it in debugger mode it is not executing after line el.submit();
I am quite sure that i am doing this wrong way, but can someone tell me what is the right approach to this and explain how to get response object which server would send after log in ?
Calling the submit() method on an input field submits the whole form (with all input values), so the following line can be deleted:
elp.submit();
If the form has a submit button, then after executing el.submit() login will be done.
I have been trying to automate a certain flow on a website, but whenever I navigate to the site a light box/window appears because of which my element is not getting selected.
I have tried 2 approaches to close the window but none of them are working:
Have tried to close the window using the pop up closing approach.
Have tried Frames approach but that isn't working as well.
Below is my code:
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
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;
public class Handle_Windows_popUP {
static WebDriver driver = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\Drvier\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://www.makemytrip.com");
Set<String> id = driver.getWindowHandles();
Iterator<String> itr = id.iterator();
System.out.println(id.size());
while(itr.hasNext())
{
Object element = itr.next();
System.out.println("id: "+element);
}
// Trying to find the 'X' button if present in any of the frame but none of the frame has it
List<WebElement> ls = driver.findElements(By.tagName("iframe"));
System.out.println("Numberof frames:"+ls.size());
for(int i=0;i<ls.size();i++)
{
driver.switchTo().frame(i);
System.out.println("Frame: "+i);
System.out.println(driver.findElements(By.xpath("*[#id='htmlDoc']/body/div[13]/div/a[1]")).size());
driver.switchTo().defaultContent();
}
// The Pop-up approach
String parent_Window = itr.next();
String child_win = null;
while(itr.hasNext())
{
child_win = itr.next();
driver.switchTo().window(child_win);
driver.close();
}
driver.switchTo().window(parent_Window).getTitle();
}
}
as this works fine if u refresh the browser, i will suggest u not to use any other code. But if u want to know how to close the window without refresh browser, write the below code after launch:
//wait until the browser loaded.
//than use this code
driver.findElement(By.cssSelector("div.appfest_container.appfest_container-bg.visible-md.visible-lg >a.appfest_container-close.pull-right.clearfix")).click();
my css path is long but u may change it by using xpath.
//*[#id="htmlDoc"]/body/div[13]/div/a[1]
and hope u will accept the answer.
I have the below code to set up an auto bid on an auction site.
I have gotten stuck as the confirm button is disabled until the user types keypresses into the text field.
I can populate the field using selenium.type however this does not remove the disabled attribute from the button.
I was hoping there might be a way of removing the attribute once the .type command has finished.
I have searched many pages to find the answer and I have found that it might be possible but for the life of me I cannot get it to work.
Could somebody please help with what I am doing wrong here:
import static org.junit.Assert.*;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
import static org.hamcrest.Matchers.containsString;
public class Bidder_Home_004 {
private Selenium selenium;
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "URL");
selenium.start();
}
#Test
public void testBidder_Home_004() throws Exception {
// Login
selenium.open("/bidderlogin");
selenium.select("id=ContentPlaceHolder1_ddlBidder", "label=A H Biler");
selenium.click("id=ContentPlaceHolder1_btnLogin");
selenium.waitForPageToLoad("30000");
selenium.click("id=hrefCurrent");
selenium.waitForPageToLoad("30000");
Thread.sleep(3000);
// End Login
// Navigate to Home page
selenium.click("//*[#id='hrefCurrent']");
selenium.waitForPageToLoad("30000");
// End Navigate to Home page
// Find Active Tab
String linkHome = selenium.getText("//li[#class='active']");
assertEquals("Igangværende", linkHome);
// End Find Active Tab
// Get Auction ID
selenium.click("//*[#id='spanWait']");
Thread.sleep(3000);
String linkAuctionlist = selenium.getValue("//*[starts-with(#id, 'liAuction')]/#id");
linkAuctionlist = linkAuctionlist.replace("liAuction", "");
// End Get Auction ID
// Get Vehicle ID
String carsinAuction = selenium.getValue("//*[1][contains(#id,'btnBidUp')]/#id");
carsinAuction = carsinAuction.replace("btnBidUp","");
// End Get Vehicle ID
//Find Original Vehicle Value
String OrgVal1 = selenium.getText("//*[#id='bidvalue_"+carsinAuction+"']");
OrgVal1 = OrgVal1.replace("kr. ", "");
OrgVal1 = OrgVal1.replace(".", "");
int OrgVal2 = Integer.parseInt(OrgVal1);
int nextBid = (OrgVal2 + 1500);
// End Find Original Vehicle Value
// Click AutoBid button
selenium.click("//*[#id='btnProxy"+carsinAuction+"']");
Thread.sleep(2000);
selenium.type("//*[#id='txtProxyBid']", ""+nextBid+"");
((JavascriptExecutor)selenium).executeScript("arguments[0].removeAttribute('disabled','disabled')");
selenium.click("//*[#id='btnSubmit']");
Thread.sleep(2000);
// End Click AutoBid button
// Find New Vehicle Value
String NewVal1 = selenium.getText("//*[#id='bidvalue_"+carsinAuction+"']");
NewVal1 = NewVal1.replace("kr. ", "");
NewVal1 = NewVal1.replace(".", "");
int NewVal2 = Integer.parseInt(NewVal1);
// End Find New Vehicle Value
String fileName = new SimpleDateFormat("ddMMyyyy'Autobid.txt'").format(new Date());
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println(NewVal2);
writer.close();
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
As you can see in the "Click Autobid Button" section I have a line that includes JavascriptExecutor - this is a line that I have found on other forums and within stackoverflow however I have not yet gotten it to work.
When I execute I have the following error:
java.lang.ClassCastException: com.thoughtworks.selenium.DefaultSelenium cannot be cast to org.openqa.selenium.JavascriptExecutor
How to solve this error issue?
For Selenium Webdriver:
Please remove following lines from your code in import section:
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
it causes to some conflicts
The reason is at your wrapper class DefaultSelenium.
for casting to JavascriptExecutor it should be distinct instance of selenium's Driver instance.
And it should looks as follows:
((JavascriptExecutor) DefaultSelenium.getDriverInstance()).executeScript()
For solving casting to JavascriptExecutor you should return explisit instance of driver (Firefox, Chrome, Opera, IE... drivers).
And this method should has signature like following:
class DefaultSelenium {
// all class stuff here
public static RemoteWebDriver getDriverInstance() {
return currentDriverInstance;
}
After you will have correct instance of Selenium RemoteWebDriver you able to cast it to JavascriptExecutor and execute JS script.
BTW:
Using Thread.sleep() is very bad style.
Much better is to use explicit waits - Explicit and Implicit Waits
I switch from window A to window B.When i try to perform an action on window B,it throws No such element exception.I am new to selenium webdriver.Please help me out.
My requirement :
1)Go to http://www.kotak.com/bank/personal-banking/convenience-banking/net-banking.html
2)Click on SECURELY LOGIN
3)Switch to the newly opened window and fill username and password in it.Locating username and password on this window throwing error.
My code :
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WindowHandler1 {
public static void main(String args[]) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
driver.get("http://www.kotak.com/bank/personal-banking/convenience- banking/net-banking.html");
Thread.sleep(5000);
driver.findElement(By.xpath(".//*[#id='label-01']/a[1]")).click();
Set<String> windowids = driver.getWindowHandles();
Iterator<String> iter = windowids.iterator();
System.out.println(windowids);
String mainWindowId = iter.next();
String tabedWindowId = iter.next();
Thread.sleep(2000L);
// switching to the new pop up window
driver.switchTo().window(tabedWindowId);
Thread.sleep(20000);
//getting no such element exception upon executing line below
driver.findElement(By.xpath(".//*[#id='Username']")).sendKeys("username");
driver.findElement(By.id("Username")).sendKeys("abc");
}
}
I had a similar problem and noticed that in the list of window handles from selenium, the order is not always the same. So in your code it looks like you are dependent on the last window in the list being the new window, when it may be the first. The solution was to make sure that the window you are trying to switch to is not the same as the current window handle.
You may be getting the NoSuchElement exception because you are not in the right window.