With Selenium WebDriver unable to switch to a popup - java

A pop will display asking to enter contact info. It is not an iframe, or alert or windows based popup. The URL does not even change. On the main homepage I click on 'Contact Us' and I get a pop up, looks like a form. How do I switch driver control to it and send input contact info??
Any help is alway highly appreciated.

I am not sure if you have a specific problem, or it's just synchronization issue (which this example would address):
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10); // used for synchronization
driver.get("http://uptake.com/");
// Make sure page was loaded
WebElement contactUs = wait.until(
ExpectedConditions.elementToBeClickable(By.linkText("Contact Us")));
contactUs.click();
// Wait for Contact Us div to become visible
// (by checking that title is displayed)
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//h2[contains(text(), 'Contact us below.')]")));
// Start filling form
driver.findElement(By.name("name")).sendKeys("John Smith");
// ... rest of the fields
driver.findElement(By.name("message")).sendKeys("Hello!");
driver.findElement(By.xpath("//input[#value='Send']")).click();

Related

Selenium: Trying to login but the same page is reloaded after click

I am trying to login a page.
I entered the e-mail & password inputs by element.sendKeys() without any error.
After that I need to click the 'loginButton' button. But the button is defined as non keyboard-focusable.
When I run the automation, the button is clicked. But the automation is not continue with the next page (main page); just reloads the same page with empty inputs.
I tried several ways to click the button and also tried to enter by using 'ENTER' key;
// **1.**
loginButton.click();
// **2.**
robot.keyPress(KeyEvent.VK_ENTER);
// **3.**
Actions act = new Actions(dDriver);
act.moveToElement(driver.findElement(By.id("loginButton"))).click().build().perform();
// **4.**
JavascriptExecutor executor;
All of them seems that I can click the button but after that as I mentioned, the page is reloaded, not continue with the next page.
What else can I try?
A problem I can think about is that you are typing the information too fast and hit the login button right away.
Try to wait before clicking the Login button 0.3 seconds:
Thread.Sleep(300);
Or even a full second:
Thread.sleep(1000);
Tell me if this solves your issue.
Also, the site might be disabled for automation code so add these to your ChromeOptions:
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
WebDriver driver = new ChromeDriver(options);
Or
options.addArguments("disable-infobars");
To click() on the element Giriş Yap you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.green_flat#loginButton"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='green_flat' and #id='loginButton'][text()='Giriş Yap']"))).click();

Not able to click on Login button using selenium webdriver and Java

Hi I am trying to automate https://www.nextgenerationautomation.com and unable to click on login / SignUp button using Selenium 4
Steps:
Navigate to URL: https://www.nextgenerationautomation.com
Click on LogIn/SignUp button.
Issue: when I am using Thread.Sleep, code is working fine but when I am using explicit wait & implicit wait it's not working.
I have added Implicit in my base class at the time of driver initialization.
Here is the code that I have tried.
public class nextGenAutomationLoginPage extends Base {
#FindBy(xpath = "(//button[#class='_1YW_5'])[1]")
WebElement login;
public nextGenAutomationLoginPage() {
super();
PageFactory.initElements(driver, this);
// TODO Auto-generated constructor stub
}
public void clickOnLogin() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
System.out.println(driver.getTitle());
// Thread.sleep(2000);
wait.until(ExpectedConditions.elementToBeClickable(login));
//wait.until(ExpectedConditions.presenceOfNestedElementLocatedBy(login, By.xpath("//div[#class='_10b1I']") ));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
js.executeScript("arguments[0].scrollIntoView();", login);
login.click();
//driver.findElement(By.xpath("(//button[#class='_1YW_5'])[1]")).click();
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//div[#id='comp-kaoxkn4a1']")));
String sign = driver.findElement(By.xpath("//div[#id='comp-kaoxkn4a1']/h1/span")).getText();
System.out.println(sign);
}
Note: I tried to add Scroll as well to add some wait before clicking.
DOM:
Please let me know if i am missing anything here.
Hi I got the point whats happening here :
Manually navigate to URL: https://www.nextgenerationautomation.com (Selenium also loading this URL)
Manually Immediately keep clicking on "LogIn/SignUp button" (Selenium also able to click therefore NO error in console )
"LogIn/SignUp" page not opening unless enter image description here (LinkedIn following count widget ) gets appear on screen
Once enter image description here gets appear manually click on "LogIn/SignUp button", now Login page is opening (Selenium able to click after Thread.Sleep)
Summery:
This is a codding defect on that page.
"LogIn/SignUp" is not clickable until enter image description here gets added on page
Your selenium code is perfectly fine :)
Xpath I have used is //span[text()='Log In / SignUp']
Thanks KS
To click() on the element with text as Log In / SignUp you can use either of the following Locator Strategies:
xpath:
driver.findElement(By.xpath("//div[starts-with(#id, 'defaultAvatar')]//following::span[text()='Log In / SignUp']")).click();
However, as the element is a dynamic element, so to click() on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[starts-with(#id, 'defaultAvatar')]//following::span[text()='Log In / SignUp']"))).click();
Actually your code is clicking the login button before the page is loaded properly. please add visibility condition.
wait.until(ExpectedConditions.visibilityOfElementLocated(by));

How to Automate new Facebook Sign up popup?

I've tried to Automate Facebook Signup page (new version consists of a popup). I've tried to switch to iframe but I've failed to find it.
Please help me. Please share the code.
The code below worked for me. Signup section is not any new pop-up window or frame. So don't need to switch to any frame or window. Just locate the fields and enter the required data using methods like sendKeys, clicks etc.
WebDriver Driver = new ChromeDriver();
Driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//Driver.manage().window().maximize();
String url = "https://www.facebook.com/";
Driver.get(url);
WebElement createAcount=Driver.findElement(By.id("u_0_2"));
createAcount.click();
WebElement firstname=Driver.findElement(By.id("u_1_b"));
firstname.sendKeys("Tina");
WebElement surname=Driver.findElement(By.id("u_1_d"));
surname.sendKeys("Roy");
I think Sign-up input fields are NOT in the iframe, so you don't need to switch.
Just doing this test. The elements are dynamically generated so they have different values everytime. Group the element selection by more attributes

Selenium -- How to wait until page is completely loaded [duplicate]

This question already has answers here:
Wait for page load in Selenium
(48 answers)
Closed 6 years ago.
I am trying to automate some test cases using Java and Selenium WebDriver. I have the following scenario:
There is a page named 'Products'. When I click on 'View Details' link
in the 'Product' page, a popup (modal-dialog) containing the details of the item appears.
When I click on the 'Close' button in the popup the popup closes and
the page automatically refreshes (the page is just reloading, the contents remain unchanged).
After closing the popup I need to click on 'Add Item' button in the
same page. But when WebDriver trying to find the 'Add Item' button,
if the internet speed is too fast, WebDriver can find and click the
element.
But if the internet is slow, WebDriver finds the button before the
page refresh, but as soon as the WebDriver click on the button, the page refreshes and StaleElementReferenceException occurs.
Even if different waits are used, all the wait conditions become true
(since the contents in the page are same before and after reload)
even before the page is reloaded and StaleElementReferenceException
occurs.
The test case works fine if Thread.sleep(3000); is used before clicking on the 'Add Item' button. Is there any other workaround for this problem?
3 answers, which you can combine:
Set implicit wait immediately after creating the web driver instance:
_ = driver.Manage().Timeouts().ImplicitWait;
This will try to wait until the page is fully loaded on every page navigation or page reload.
After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. Sample code:
C#
new WebDriverWait(driver, MyDefaultTimeout).Until(
d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
Java
new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
Check if the URL matches the pattern you expect.
It seems that you need to wait for the page to be reloaded before clicking on the "Add" button.
In this case you could wait for the "Add Item" element to become stale before clicking on the reloaded element:
WebDriverWait wait = new WebDriverWait(driver, 20);
By addItem = By.xpath("//input[.='Add Item']");
// get the "Add Item" element
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(addItem));
//trigger the reaload of the page
driver.findElement(By.id("...")).click();
// wait the element "Add Item" to become stale
wait.until(ExpectedConditions.stalenessOf(element));
// click on "Add Item" once the page is reloaded
wait.until(ExpectedConditions.presenceOfElementLocated(addItem)).click();
You can do this in many ways before clicking on add items:
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(By.id("urelementid"))); // instead of id you can use cssSelector or xpath of your element.
or:
wait.until(ExpectedConditions.visibilityOfElementLocated("urelement"));
You can also wait like this. If you want to wait until invisible of previous page element:
wait.until(ExpectedConditions.invisibilityOfElementLocated("urelement"));
Here is the link where you can find all the Selenium WebDriver APIs that can be used for wait and its documentation.
yes stale element error is thrown when (taking your scenario) you have defined locator strategy to click on 'Add Item' first and then when you close the pop up the page gets refreshed hence the reference defined for 'Add Item' is lost in the memory so to overcome this you have to redefine the locator strategy for 'Add Item' again
understand it with a dummy code
// clicking on view details
driver.findElement(By.id("")).click();
// closing the pop up
driver.findElement(By.id("")).click();
// and when you try to click on Add Item
driver.findElement(By.id("")).click();
// you get stale element exception as reference to add item is lost
// so to overcome this you have to re identify the locator strategy for add item
// Please note : this is one of the way to overcome stale element exception
// Step 1 please add a universal wait in your script like below
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // just after you have initiated browser
There are two different ways to use delay in selenium one which is most commonly in use. Please try this:
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
second one which you can use that is simply try catch method by using that method
you can get your desire result.if you want example code feel free to contact me defiantly I will provide related code

Selenium WebDriver- Java- It is not willing to click a link

I have tried, quite a lot and I am not even getting any sort of errors but it is not printing anything (I want it to print the title of the page)
WebDriver driver = new HtmlUnitDriver();
WebElement element = driver.findElement(By.cssSelector("a[href*='Alerts.htm']"));
element.click();
System.out.println(driver.getTitle());
Here is the HTML code (the part I wish to click), there is a title for both , the page I want to click and the current page.
<li title="Alerts"><span>Alerts</span></li>
I am not any errors but it should print the title, which it is not doing.
I have followed many sorts of instructions found here and on the web.
Things I have tried so far:
By locator = By.xpath("//li[#title='Alerts']/a");
WebElement element = driver.findElement(locator);
element.click();
WebElement element = driver.findElement(By.partialLinkText("Alert"));
element.click();
Where am I going wrong?
The title of an HTML document is defined within a <title> tag, typically in the <head> section.
This is the title that the getTitle method returns.
See http://www.w3schools.com/tags/tag_title.asp.
I am not sure of this. But I think HTMLUnitDriver is a headless browser instance. Kindly try in another browser, firefox perhaps.
WebDriver driver = new FirefoxDriver();
You first need to open a page in a browser!
WebDriver driver = new ...
driver.get(url) // THIS LAUNCHES AN ACTUAL BROWSER
// now you can actually do things
driver.findElement ...
driver.getTitle()
driver.quit() // TO DISMISS THE BROWSER

Categories