I'm trying to simulate a few clicks for my new program but I'm stuck on the last thing!
I've managed to make selenium open the page and click on the checkbox which shows a rectangle popup with 9 buttons inside it. The only problem is clicking the buttons inside the pop up! I've checked the xpath a few times but Selenium says "No such element"
Here is my code:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class test {
static WebDriver driver;
public static void main(String[] args) {
ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("default");
driver = new FirefoxDriver(myprofile);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.runelocus.com/top-rsps-list/vote-1858-GrinderScape%20-%20New%20Website%20and%20Great%20Updates!/");
driver.switchTo().frame(1);
driver.findElement(By.xpath("//*[#id='recaptcha-anchor']/div[5]")).click();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.findElement(By.cssSelector("#rc-imageselect-target > table > tbody > tr:nth-child(1) > td:nth-child(2)")).click();
}
}
Link to the problem: http://www.runelocus.com/top-rsps-list/vote-1858-GrinderScape%20-%20New%20Website%20and%20Great%20Updates!/
EDIT:
It creates the new elements after you click the checkbox. How would I click them?
Element you are trying to click is in iframe. We need to switch explicitly to that iframe for selenium to locate that element. Below code worked for me. (Please format Xpath in better readable format.)
driver.get("http://www.runelocus.com/top-rsps-list/vote-1858-GrinderScape%20-%20New%20Website%20and%20Great%20Updates!/");
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
WebElement iframeSwitch = driver.findElement(By.xpath("/html/body/section/div/div/section/div/article/div/div[2]/form/table/tbody/tr/td[1]/div/div/div/iframe"));
driver.switchTo().frame(iframeSwitch);
System.out.println("Switched");
driver.findElement(By.cssSelector("div[class=recaptcha-checkbox-checkmark]")).click();
Related
I am trying to drag and drop using Selenium Java. It is clicking but not dropping it in the destination specified.
Code used for dragging and dropping:
WebElement drag= driver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div[2]/vr-modalbody/div/vr-form/div/vr-validation-group/vr-tabs/vr-tab[3]/vr-row/div/vr-columns/div/vr-validation-group/div/vr-directivewrapper/vr-rules-normalizenumbersettings/div/vr-row[1]/div/vr-columns/div/vr-toolbox/div/div[3]"));
//Drop
WebElement Drop= driver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div[2]/vr-modalbody/div/vr-form/div/vr-validation-group/vr-tabs/vr-tab[3]/vr-row/div/vr-columns/div/vr-validation-group/div/vr-directivewrapper/vr-rules-normalizenumbersettings/div/vr-row[2]/div/vr-columns/div/div[2]/div/vr-validator/div/div[1]/vr-datagrid/vr-datagridrows/div[1]/div/div[2]/div[1]"));
Actions actions= new Actions(driver);
actions.clickAndHold(drag).build().perform();
actions.moveToElement(Drop).build().perform();
actions.release(Drop).build().perform();
If this is not working, please share URL or page source code.
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
public class DragAndDropTest extends WebDriverSetup {
public static void main (String[] args) {
WebDriver driver = startChromeDriver(); // standard driver setup just wrapped
driver.get("https://demoqa.com/droppable/");
WebElement draggable = driver.findElement(By.id("draggable"));
WebElement droppable = driver.findElement(By.id("droppable"));
Actions actions = new Actions(driver);
actions.dragAndDrop(draggable, droppable).build().perform();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
driver.quit();
}
}
First, you have to move to the element you want to drag. Besides, you can use chaining.
...(your codes are above)
actions.moveToElement(drag)
.clickAndHold()
.moveToElement(Drop)
.release(Drop).perform();
try {
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(drag));
Actions actions = new Actions(driver);
actions.clickAndHold(drag).build().perform();
actions.moveToElement(Drop).build().perform();
actions.release(Drop).build().perform();
} catch (Exception e) {
System.out.println("Error occurred while dragging and dropping: " + e.getMessage());
}
I am learning Selenium and using jetblue.com for test. When I click on "FIND IT" button in homepage by providing all the required values, the page simply refreshes instead of going to the next screen. Can anyone advise where I am going wrong?
I tried using .click() and submit(). but not the control does not go the next page
package testCases;
import java.util.List;
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;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
public class Calendar {
#Test
public void calControl() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver","C:\\chromedriver_win32\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--start-maximized");
WebDriver driver= new ChromeDriver(options);
driver.get("https://www.jetblue.com");
// driver.findElement(By.className("input-group-btn")).click();
Thread.sleep(3000);
// driver.findElement(By.cssSelector("button[class='btn pull-right']")).click();
List<WebElement> count = driver.findElements(By.className("input-group-btn"));
int count1 = driver.findElements(By.className("input-group-btn")).size();
count.get(0).click();
Thread.sleep(3000);
driver.findElement(By.xpath("//table[#class='calendar']//td//span[.=27]")).click();
System.out.println(count1);
for (int i = 0;i<count1;i++)
{
System.out.println(count.get(i).toString());
}
Thread.sleep(3000);
count.get(1).click();
Thread.sleep(3000);
//driver.findElement(By.xpath("//button/span[#class='foreground-sprite-calendarforward']")).click();
List<WebElement> pullRight = driver.findElements(By.cssSelector("button[class='btn pull-right']"));
int count2 = driver.findElements(By.cssSelector("button[class='btn pull-right']")).size();
do
{
pullRight.get(1).click();
} while (driver.findElement(By.xpath("//div/strong[.='March 2018']")).isDisplayed()==false);
List<WebElement> returnDate = driver.findElements(By.xpath("//table[#class='calendar']//td//span[.=8]"));
int returnCount = driver.findElements(By.xpath("//table[#class='calendar']//td//span[.=3]")).size();
returnDate.get(1).click();
//driver.findElement(By.xpath("//input[#class='piejs']")).click(); Find Button
WebElement from = driver.findElement(By.id("jbBookerDepart"));
from.click();
Thread.sleep(2000);
from.sendKeys("DXB");
from.sendKeys(Keys.TAB);
Thread.sleep(2000);
WebElement to = driver.findElement(By.id("jbBookerArrive"));
to.click();
Thread.sleep(2000);
to.sendKeys("SFO");
to.sendKeys(Keys.TAB);
Thread.sleep(2000);
WebElement findButton = driver.findElement(By.xpath("//*[#id='login-search-wrap']/div[3]/div/div[3]/form/input[5]"));
//System.out.println("Value of button:" +driver.findElement(By.xpath("//*[#id='login-search-wrap']/div[3]/div/div[3]/form/input[5]")).toString());
/*Actions a = new Actions(driver);
//a.click(findButton).build().perform();
a.clickAndHold(findButton).doubleClick().build().perform();*/
/*driver.findElement(By.cssSelector("input[value='Find it']")).submit();
driver.findElement(By.xpath("input[value='Find it']")).submit();*/
System.out.println(findButton.isEnabled());
findButton.click();
Thread.sleep(5000);
}
}
That page is probably using anti-selenium software. I debugged your code several times, and here are my observations - I tried do perform some operations by hand, and some by WebDriver, and the result is: If ANY operation is performed by WebDriver, the form will not submit. That even includes opening of the page. They probably set some flag whenever an automated software is performing any action on their page.
Have a look at this answer. I don't know what anti-bot method they may be using, but this could be the first step.
I am trying to learn selenium by testing them on different websites. In this process, I am trying to work with Flipkart website. In this, I would like to give puma is search bar and trying to click one of the resultant items. But I am not able to do that using below-mentioned code. Could anyone help in solving it?
Secondly, If we click on any item, it is redirected to new-tab. How to access the new-tab elements using the same script?
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
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;
public class AutomationTesting {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","/Users/xxxx/eclipse-workspace/seleniumTesting/lib/geckoDriver/geckodriver");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.de");
driver.findElement(By.id("lst-ib")).sendKeys("flipkart");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Flipkart")));
driver.findElement(By.partialLinkText("Flipkart")).click();
driver.findElement(By.cssSelector("._3Njdz7 [class = '_2AkmmA _29YdH8']")).click();
driver.findElement(By.xpath("//input[#class = 'LM6RPg']")).click();
driver.findElement(By.xpath("//input[#class = 'LM6RPg']")).sendKeys("Puma");
driver.findElement(By.xpath("//button[#class = 'vh79eN']")).click();
driver.findElement(By.xpath("//a[#title='Puma Men Black Wallet' and #class= '_1Nyybr _30XEf0']")).click();
}
}
You need to use the window switchTo feature.
String mainWindowHandle = driver.getWindowHandle();
ArrayList<String> wins = driver.getWindowHandles();
// You can use a for loop here, or get the assumed second window directly
driver.switchTo().window(wins.get(1));
// Test some things, then switch back
driver.close();
driver.switchTo().window(mainWindowHandle);
See http://www.seleniumhq.org/docs/03_webdriver.jsp#moving-between-windows-and-frames
You will have to inspect that entire frame. I would suggest instead of customising xpaths on your own try firebug and firepath add on of Firefox for getting xpath of entire elements. Inspect the entire frame within which the results are getting displayed then save it in some variable like below one:
List<WebElements> searchResults;
searchResults=driver.findElements(By.xpath("Your xpath"));
Then access elements of this list using index and then you can perform .click() action on the same. More on this link for capturing xpath using firebug and firepath
Question 1: During the execution of the last line in the above code I am getting the following error. Unable to locate element: //a[#title='Puma Men Black Wallet' and #class= '_1Nyybr _30XEf0']
--> Due to Lazy loading webelement not present in dom at the time when you are hiting click event on it. So to over come this you need to make the webElement on view and then hit the click event.
Please refer below code:-
driver.get("https://www.google.de");
driver.findElement(By.id("lst-ib")).sendKeys("flipkart");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
WebDriverWait wait = new WebDriverWait(driver,60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Flipkart")));
driver.findElement(By.partialLinkText("Flipkart")).click();
try{
driver.findElement(By.cssSelector("._3Njdz7 [class = '_2AkmmA _29YdH8']")).click();
}catch(Exception e){
System.out.println("No division");
}
driver.findElement(By.xpath("//input[#class = 'LM6RPg']")).click();
driver.findElement(By.xpath("//input[#class = 'LM6RPg']")).sendKeys("Puma");
driver.findElement(By.xpath("//button[#class = 'vh79eN']")).click();
// Thread.sleep(3000);
wait.until(ExpectedConditions.visibilityOf( driver.findElement(By.xpath("//a[#title='Puma Men Black Wallet']"))));
// getting element into view
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", driver.findElement(By.xpath("//*[#alt='Puma Men Black Wallet']")));
Thread.sleep(2000);
driver.findElement(By.xpath("//*[#alt='Puma Men Black Wallet']")).click();
Question 2: If that last command works then it is redirected to the new tab. So how to access the elements from the new-tab?
--> As suggested be #Damian Jansen add that code after last click event.
String mainWindowHandle = driver.getWindowHandle();
ArrayList<String> wins = driver.getWindowHandles();
for(String win : wins ){
driver.switchTo().window(win);
// other operation
System.out.println(driver.getTitle());
}
// back to old window
driver.switchTo().window(mainWindowHandle);
System.out.println(driver.getTitle());
Hope this help you :)
Use this code to reach upto puma and then select the option use below code
public static void main(String[] args) throws InterruptedException, AWTException {
System.setProperty("webdriver.chrome.driver","G:\\java programme\\SendkeysExample\\lib\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.google.com");
driver.findElement(By.id("lst-ib")).sendKeys("flipkart");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
driver.findElement(By.linkText("Flipkart")).click();
driver.findElement(By.className("LM6RPg")).sendKeys("Puma");
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_DOWN);
rb.keyPress(KeyEvent.VK_DOWN);
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_DOWN);
rb.keyRelease(KeyEvent.VK_DOWN);
rb.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(2000);
/*driver.findElement(By.xpath(".//*[#id='container']/div/header/div[1]/div/div/div/div[1]/form/ul/li[2]/a"));
driver.findElement(By.className("icon-add-circle"))*/;
driver.close();
}
}
Requirement: Go to the link which is a job search for last 3 days.
1) Print job descriptions
2) Click on the next link to go to next page until you reach the last page
Problem: I am using try catch for no such element found for next link when I reach the last page. Using this solution it stops the script, by looking at the JUNIT bar you will not know if the test passed or failed.It is a grey bar since as I used exit. How can I make this code better so that I do not have to use that try catch and see a green bar for a passing test?
Code:
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class QAJob {
#Test
public void jobSearch(){
WebDriver driver= new FirefoxDriver();
driver.get("https://www.indeed.com/jobs?as_and=qa+engineer&as_phr=&as_any=&as_not"
+ "=&as_ttl=&as_cmp=&jt=all&st=&salary=&radius=10&l=Bellevue%2C+WA&fromage=7&limit"
+ "=10&sort=date&psf=advsrch");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//code to scroll down to find the rest pages link
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollBy(0,1000)", "");
// Find and print the number of pages for the search
List<WebElement> search_pages=driver.findElements(By.xpath("//div [contains(#class,'pagination')]//a"));
System.out.println("Number of pages found for this search " + search_pages.size());
while(search_pages.size()!=0){
List<WebElement> job_desc=driver.findElements(By.xpath("//div [contains(#id,'p')][contains(#class,'row')]"));
for(WebElement e:job_desc){
String str_job_desc=e.getText();
System.out.println(str_job_desc);
}
try
{
// closes the pop up that appears
driver.findElement(By.id("popover-x-button")).click();
}
catch (Exception e)
{
}
try
{
//click on next link to go to next page
driver.findElement(By.xpath("//span[contains(#class,'np')][contains(text(),'Next')]")).click();
//scroll down
JavascriptExecutor jse1 = (JavascriptExecutor) driver;
jse1.executeScript("window.scrollBy(0,1000)", "");
}
//when I get the exception(because no next link is available) exit.
catch (org.openqa.selenium.NoSuchElementException e)
{
System.exit(0);
}
}
}
}
Thanks in advance for your time and suggestion.
You can actually re-use the trick used in your code to avoid try-catch block
List<WebElement> popXButton=driver.findElements(By.id("popover-x-button"));
if (popXButton.size()>0){
driver.findElement(By.id("popover-x-button")).click();
}
Same extends to the next block too
List<WebElement> nextVal=driver.findElements(By.xpath("//span[contains(#class,'np')][contains(text(),'Next')]"));
if(nextVal.size()>0){
driver.findElement(By.xpath("//span[contains(#class,'np')][contains(text(),'Next')]")).click();
}
else{
break;//exits while loop!
}
I have created two sets of code contained in two seperate classes
Task Required: need to click on the 'Cash' button on the PH payment page.
Class one = simple class, simple code = code works and can click on the cash option.
Class two = setup contains page objects, framework uses different structure = code is unable to click on the cash option when reaching the payment page = 'org.openqa.selenium.StaleElementReferenceException: Element not found in the cache'
I have used the same locators within both classes but when uses the correct locator in '2' its unable to click on the 'radio' button; as listed above i get the listed error; i have tried to create bespoke methods; using loops etc and different locators but nothing works.
Working code and class:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class TestClass {
#Test
public void test() throws InterruptedException {
//System.setProperty("webdriver.chrome.driver", "C:\\Users\\GBruno\\Desktop\\masteringSelenium\\Framework\\src\\test\\resources\\chromedriver.exe");
// WebDriver driver = new ChromeDriver();
WebDriver driver = new FirefoxDriver();
driver.get("http://www.pizzahut.co.uk");
driver.manage().window().maximize();
//click pizza button
driver.findElement(By.cssSelector("div[id='page'] [href='/menu/pizza']")).click();
//select any pizza to start order
driver.findElement(By.cssSelector("div[class='col-xxs-8 col-xs-6 col-sm-8 col-md-7 col-lg-6'] *> button")).click();
//enter postcode and find hut
Thread.sleep(2000);
driver.findElement(By.cssSelector("#ajax-postcode-txt")).sendKeys("TS1 4AG");
driver.findElement(By.cssSelector(" #get-store-btn")).click();
//click start order button
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='store-collection-section']/div[2]/div[4]/div[4]/div/a")).click();
//add pizza
Thread.sleep(5000);
driver.findElement(By.xpath(".//*[#id='pizza-product-list']/div/div[1]/div/div[2]/div[2]/div[3]/div/form/button")).click();
//click mini basket
driver.findElement(By.xpath("html/body/nav/div/div/div[3]/div/div[1]/div[2]/span[3]")).click();
Thread.sleep(2000);
//click checkout
driver.findElement(By.xpath(".//*[#id='divBasket']/div[1]/div/div[2]/div[2]/a")).click();
Thread.sleep(2000);
//checkout guest & enter details
driver.findElement(By.xpath(".//*[#id='frmCheckout']/div[2]/div/div[1]/a")).click();
driver.findElement(By.xpath(".//*[#id='ddlTitleSelectBoxIt']")).click();
driver.findElement(By.linkText("Mr")).click();
driver.findElement(By.xpath(".//*[#id='FirstName']")).sendKeys("Tom");
driver.findElement(By.xpath(".//*[#id='LastName']")).sendKeys("Hanks");
driver.findElement(By.xpath(".//*[#id='EmailAddress']")).sendKeys("tom_hanks12344566#mail.com");
driver.findElement(By.xpath(".//*[#id='ConfirmEmailAddress']")).sendKeys("tom_hanks12344566#mail.com");
driver.findElement(By.xpath(".//*[#id='PhoneNumber']")).sendKeys("01234 5647890");
driver.findElement(By.xpath(".//*[#id='btnFindAddress']")).click();
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='ddlAddressesToChooseSelectBoxItArrowContainer']")).click();
driver.findElement(By.linkText("K F C 189-191 Linthorpe Road Middlesbrough TS14AG")).click();
driver.findElement(By.xpath(".//*[#id='btnContinue']")).click();
driver.findElement(By.xpath(".//*[#id='payment-methods']/div[1]/div/label/input")).click();
}
}
Code dosnt work:
public void selectPaymentTypeAndPayForOrder() throws Exception {
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='payment-methods']/div[1]/div/label/input")).click();
driver.findElement(By.cssSelector(" form[id='CheckoutForm'] input[data-paymentname='Cash']")).click();
The following code resolved the issue:
List<WebElement> iframes = driver.findElements(By.tagName("iframe"));
if(iframes.size() == 0) {
Assert.fail();
} else {
// Frames present
Assert.assertTrue(true);
}