Selenium cant access a hidden element - java

breaking my head over the following piece of code in Java, trying to solve a recaptcha for my selenium tests at work before implementing them.
The use case I use: https://www.google.com/recaptcha/api2/demo
WebDriver driver = Selenium.getInstance();
Selenium.goToWebPage("https://www.google.com/recaptcha/api2/demo");
WebDriverWait wait = new WebDriverWait(driver, 5);
List<WebElement> allIFrames = SeleniumUtil.getWebElementNicelyByTagName(driver, wait, "iframe");
if(allIFrames == null){
return;
}
Optional<WebElement> captchaIFrame = allIFrames.stream().filter(webElement -> webElement.getAttribute("src").contains("recaptcha/api2/anchor")).findFirst();
if(!captchaIFrame.isPresent()){
return;
}
WebDriver frame = driver.switchTo().frame(captchaIFrame.get());
//System.out.println(frame.getPageSource());
WebElement recaptchaTokenElement = SeleniumUtil.getWebElementNicelyByXPath(frame, wait, "//*[#type='hidden']");
System.out.println(recaptchaTokenElement);
So with the system.outs i'm trying to find my way to the captcha token, but every time it returns a null element. What the SeleniumUtil so far does is mainly:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
return driver.findElement(By.xpath(xpath));
And the same for By.CssSelector etc.
I am already in the right IFrame, because the page source is printen out correctly, but searching by #recaptcha-token (cssselector), recaptcha-token (id), //*#id="recaptcha-token" does not work.
Maybe someone can help me with this?

There is a iFrame where the driver needs to be switched to.
After few tries I've got:
standard chromedriver setup:
package selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class WebDriverSetup {
public static String userDir = System.getProperty("user.dir");
public static String chromedriverPath = userDir + "\\resources\\chromedriver.exe";
public static WebDriver driver;
public static WebDriver startChromeDriver() {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
return driver;
}
}
And getting the token:
package selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class GoogleRecaptchaDemo extends WebDriverSetup {
public static void main(String[] args) {
WebDriver driver = startChromeDriver();
driver.get("https://www.google.com/recaptcha/api2/demo");
List<WebElement> frames = driver.findElements(By.tagName("iframe"));
driver.switchTo().frame(frames.get(0));
WebElement rc = driver.findElement(By.id("recaptcha-anchor-label"));
rc.click();
WebElement recaptchaToken = driver.findElement(By.id("recaptcha-token"));
String token = recaptchaToken.getAttribute("value");
System.out.println(token);
driver.quit();
}
}
My output, last line is the token:
Starting ChromeDriver 86.0.4240.22 (398b0743353ff36fb1b82468f63a3a93b4e2e89e-refs/branch-heads/4240#{#378}) on port 25872
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Pro 01, 2020 4:30:45 ODP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
03AGdBq24MumCzjDlQCrcb4N3BuIiHm6O7V5IKSNGP1wChYe9g1Vc1GR7_NsvKqKV1Jzb5yLUXCB-ko8satP3fgkXIZ1rbjz76FITaLRRZqRJteQdVzlyzYoUgsSWQ_xjCspDvKNl6uTRGP7EzhesblTBf7HyYmjDU26BZkji8NqMFypQUzUIWUE6CF1W_UeiGCwV4Cfr2UduHJPskDubiwT7jxhRrLKFF_nK8zruV9dStwynSGzrMjwtemZSZmj2ZVJPiTxiYIV2QRIPUYPQ7dXMezrqJDG2Vwn2M9AxHOacoFcBTDIiFYoENq11-jNDJTY0a8PWl6bixpqv1itwTJw4FYnz9vSAQUCztQf7WXPLFgxp8iHjqB-uSIY39ikLJfa_rkFOke90PkF7sRlsKoQjptp_uCpJJ6aktscF97lGWA7EXJfpuOxaCMRt3VkuDZ9mzA5RFiHnQOX9I8VFWWe03t71r69aoj5y1dNoFUVT29lMsZf-X3y00eUxlLiT4JZzRFPfbF1fd4bqdH3SzpvWROxHe-IGRFz7Z_C4Hf7oNCQSXfpus2DIm2INW-JRPgfqZ_XQTaxphinGcoJ3EMvWZo6a3qDFYUB06HduULNO_5GwZ_eHUxE1wvXxGHdq2uoJ4Bkzzfu01ZD2Q13gJ6Mslup5dZlqAQGNggJY9aJYbmnRKNnUCtSY5Y8xHMr3Lnt_07SuFc_UdEDSV_KdtwgpVWEFL8OgAFP_KZaFqdaeUq_CTnHpHiTcAhNosT7V_H4gKx0A4BgHnI5NVxsLU1p09OOZ0GLJMqeP174pl03EpQy9iqnv0_e-w7NUeO7ZFgETt_pvEbqR6VqjfDO35BNd4aItzer9IdiSfzjdIAR6c0Z3_36o1WQyLXQZv_xTuZXaRYoZUTtV38aG3z5uK-pyRnNDqMZGffy5DPUn4WrDMnPM9lfI5nRZwXS503KJas54w4d0fRrZWOyhxYWeiCYhFJMDDwpqHJAzDlIqwPbQX90vVum0zEaJd_TU0l9t5QioUAwb3BuEdTeaOI8gM2OcpBScsQYTioMivi8-eRYpPvJIP239DJz6Rp5Ptk_52kC4_2rAWuG_cocuco_cA61yE3yu2WCw_e1EauOM3Ug2nGeFKFxZZdGWPdNj0E3YA3N6f3IaJYWHrQAz4odFQZaD-HZ4qnRZlJlnMzV31_o3_NLl-_2CGSywE8kuJf8wAIIplncfDdHSIlUn7WhrIOrSOX83NdKaQYAlTqLI9CTSTjaA3AyhG5OcF2dukVeACOItczNBSJcZeenTMCo1Es986nt770A3tQYC7S9r2ESxlYJl-eWGo8SKuM9udx7ZuO5lKgW-V-EUg1I-YFSoguRmGzUK-liu2-afTBn4X-97VXuiv-tdcKdi9Bx4DtlhqzNGvVbQmIOND

Related

I tried to press Ctrl+T using Selenium (Java) in the Chrome browser

I tried to press Ctrl+T using Selenium (Java) in the Chrome browser. There is no error in the console, but the browser does not open a new tab. I want to know why this happens. I tried to find on Stack Overflow, but I didn't find any accurate answer.
This is my code:
package automation1;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class Action {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\asus\\OneDrive\\Desktop\\Jar\\chromedriver_win32\\chromedriver.exe");
WebDriver chromedriver = new ChromeDriver();
chromedriver.get("https://xenodochial-meninsky-118d47.netlify.app/");
chromedriver.manage().window().fullscreen();
Actions a = new Actions(chromedriver) ;
Thread.sleep(3000) ;
a.sendKeys(Keys.CONTROL +"t").build().perform() ;
}
}
Why doesn't this not open a new tab in the Chrome browser?
There is a solution without using org.openqa.selenium.interactions.Actions.
For selenium 3.141.59:
pom.xml dependency:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
Code:
package tests;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class TejveerNaruka {
public static void main(String[] args) {
String chromedriverPath = System.getProperty("user.dir") + "\\resources\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
options.addArguments("--start-maximized");
options.addArguments("--disable-notifications");
WebDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
driver.get("https://www.stackoverflow.com");
System.out.println(driver.getTitle());
// open new tab using javascript
jsExecutor.executeScript("window.open()");
// get Window handles, identifications of all browser tabs and windows
List<String> windowHandles = new ArrayList<String> (driver.getWindowHandles());
// switch to second tab
driver.switchTo().window(windowHandles.get(1));
// prints title of the second tab (empty line)
System.out.println(driver.getTitle());
// navigate driver in the second tab
driver.get("https://www.zemancountdown.cz/");
// prints title of the second tab
System.out.println(driver.getTitle());
// close second tab
jsExecutor.executeScript("window.close()");
// switch to the first tab
driver.switchTo().window(windowHandles.get(0));
//prints title of the first tab
System.out.println(driver.getTitle());
driver.quit();
}
}
Output:
Starting ChromeDriver 108.0.5359.71 (1e0e3868ee06e91ad636a874420e3ca3ae3756ac-refs/branch-heads/5359#{#1016}) on port 18498
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Pro 12, 2022 12:50:43 ODP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Stack Overflow - Where Developers Learn, Share, & Build Careers
Miloš Zeman Countdown
Stack Overflow - Where Developers Learn, Share, & Build Careers
Another example now with selenium 4:
pom.xml dependency:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.7.1</version>
</dependency>
Code:
package tests;
import java.time.Duration;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class TejveerNaruka {
public static void main(String[] args) {
String chromedriverPath = System.getProperty("user.dir") + "\\resources\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
options.addArguments("--start-maximized");
options.addArguments("--disable-notifications");
WebDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// navigate driver and print title
driver.get("https://www.stackoverflow.com");
System.out.println(driver.getTitle());
// create second driver in new tab
WebDriver driver2 = driver.switchTo().newWindow(WindowType.TAB);
// prints empty line
System.out.println(driver2.getTitle());
// navigate driver2 and print title
driver2.get("https://www.zemancountdown.cz/");
System.out.println(driver2.getTitle());
driver2.quit();
driver.quit();
}
}
Output:
Starting ChromeDriver 108.0.5359.71 (1e0e3868ee06e91ad636a874420e3ca3ae3756ac-refs/branch-heads/5359#{#1016}) on port 24322
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Stack Overflow - Where Developers Learn, Share, & Build Careers
Miloš Zeman Countdown

how to resolve this problem cannot convert from ChromeDriver to WebDriver

public static void main(String[] args) {
String browserName = "chrome";
WebDriver driver = null;
if (browserName.equalsIgnoreCase("chrome")) {
driver = new ChromeDriver();
} else if (browserName.equalsIgnoreCase("edgebrowser")) {
driver = new EdgeDriver();
i write exactly but still am getting mismatch error
rename your class
add import org.openqa.selenium.WebDriver
add property webdriver.chrome.driver
Code:
package selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
public class Gayatri {
public static String chromedriverPath = System.getProperty("user.dir") + "\\resources\\chromedriver.exe";
public static void main(String[] args) {
String browserName = "chrome";
WebDriver driver = null;
if (browserName.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
driver = new ChromeDriver();
} else if (browserName.equalsIgnoreCase("edgebrowser")) {
driver = new EdgeDriver();
}
driver.get("https://www.stackoverflow.com");
System.out.print(driver.getTitle());
driver.quit();
}
}
Output:
Starting ChromeDriver 100.0.4896.60 (6a5d10861ce8de5fce22564658033b43cb7de047-refs/branch-heads/4896#{#875}) on port 19334
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Kvě 02, 2022 8:15:46 DOP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Stack Overflow - Where Developers Learn, Share, & Build Careers

How to determine if an element is displayed on screen for specific time using selenium java/python?

There is an webelement(Success or failure message) which gets displayed on screen only for 3 seconds. How can I assure that the element is displayed on screen for 3 seconds using selenium java OR python?
You can use java.time.LocalDateTime and java.time.temporal.ChronoUnit combine with org.openqa.selenium.support.ui.ExpectedConditions.
In this example the time a button is not enabled is measured:
package selenium;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
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.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class DeviTimeTest {
public static String userDir = System.getProperty("user.dir");
public static String chromedriverPath = userDir + "\\resources\\chromedriver.exe";
public static WebDriver driver;
public static void main(String[] args) {
WebDriver driver = startChromeDriver();
driver.get("https://demoqa.com/dynamic-properties");
LocalDateTime start = LocalDateTime.now();
WebElement button = driver.findElement(By.id("enableAfter"));
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(button));
LocalDateTime finish = LocalDateTime.now();
System.out.println("Button was disabled for " + ChronoUnit.MILLIS.between(start, finish) + " ms.");
driver.quit();
}
public static WebDriver startChromeDriver() {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
options.addArguments("--start-maximized");
options.addArguments("--disable-notifications");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
Output:
Starting ChromeDriver 96.0.4664.45 (76e4c1bb2ab4671b8beba3444e61c0f17584b2fc-refs/branch-heads/4664#{#947}) on port 47769
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Pro 06, 2021 8:00:55 DOP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Button was disabled for 4404 ms.

How to effectively change the browser name of the WebDriver object?

I intend to perform some tests by using selenium with multiple web browsers. To distinguish between the different web drivers, I use the following line of code:
((RemoteWebDriver) driver).getCapabilities().getBrowserName();
This will return a String indicating the web browser that is used by the driver object. However, for my Opera WebDriver object this will give me the String 'chrome'. I have tried changing this by explicitly setting the browser name to 'opera' using DesiredCapabilities:
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName("opera");
WebDriver driver = new OperaDriver(capabilities);
Unfortunately, this does not fix my problem. How do I effectively change the web browser name?
Your basic requirement is to identify browser initialization if I'm right, which can be done by getting user-agent from your browser using JavascriptExecutor as following:
String userAgent = (String) ((JavascriptExecutor) driver).executeScript("return navigator.userAgent;");
//following is for identifying opera browser initialization
if(userAgent.contains("OPR/"){
System.out.println("Browser currently in use is Opera");
}
Similarly you can identify other browser initilisation by referring this link
Unfortunately , you would not be able to change the BrowserName.
What instead you can try is to create function for specifically handling multiple browsers: -
package multiBrowser;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.testng.annotations.Parameters;
public class MultiBrowserClass {
WebDriver driver;
#Test
#Parameters("browser")
public void multiBrowsers(String browserName) throws InterruptedException{
if(browserName.equalsIgnoreCase("firefox")){
System.setProperty("webdriver.firefox.marionette","D:\\My Work\\Setup\\JAR\\geckodriver.exe");
ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("default");
driver = new FirefoxDriver(myprofile);
}
if(browserName.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", "D:\\My Work\\Setup\\JAR\\driver\\chromedriver.exe");
driver = new ChromeDriver();
}
else if(browserName.equalsIgnoreCase("IE")){
System.setProperty("webdriver.ie.driver", "D:\\My Work\\Setup\\JAR\\driver\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
else if(browserName.equalsIgnoreCase("opera")){
System.setProperty("webdriver.opera.driver", "D:\\My Work\\Setup\\JAR\\driver\\operadriver.exe");
driver = new OperaDriver();
}
driver.manage().window().maximize();
driver.navigate().to("https://");
System.out.println(driver.getTitle());
driver.findElement(By.xpath("//div[#id='navbar-main']/ul/li[5]/a")).click();
driver.findElement(By.xpath("//div[#id='navbar-main']/ul/li[5]/ul/li/a")).click();
Thread.sleep(3000);
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys("abc#mm.kk");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("1qaz2wsx");
Thread.sleep(3000);
driver.findElement(By.xpath("//form[#id='loginform']/div[8]/button")).click();
Thread.sleep(5000);
if(driver.getPageSource().contains("Welcome abc#mm.kk")){
System.out.println("User Successfully logged in");
}else{
System.out.println("Username or password you entered is incorrect");
}
driver.quit();
}
}
=======

Firefox webdriver not starting, driver showing as Null

driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(URL);
I'm trying to run my test in Firefox using version 46.0.1 and webdriver 2.53.0 but when I run the test I see Firefox start and then close very quickly. I've got all other browsers to work and am at a loss as to what I'm missing here.
#BeforeClass
public static void setUp() {
System.out.println("****************");
System.out.println("launching Browser");
driver = new FirefoxDriver();
driver.get("url");
#Test
public void testPageTitleInBrowser() {
FirstPage firstPage = PageFactory.initElements(driver, FirstPage.class);
firstPage
.logIn(username, password)
.clickHolidayLink()
.completeHolidayFormAndSubmit("12/05/2016");
}
#AfterClass
public static void tearDown() {
if (driver != null) {
System.out.println("Closing browser");
driver.quit();
}
}
Mainpage has been changed to firstpage
import com.google.common.annotations.VisibleForTesting;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import static Internal.BaseTest.driver;
public class FirstPage {
#VisibleForTesting
#FindBy(id = "ctl00_MCPH_MainLogin_UserNameTextBox")
WebElement usernameInput;
#VisibleForTesting
#FindBy(id = "ctl00_MCPH_MainLogin_PasswordTextBox")
WebElement passwordInput;
#VisibleForTesting
#FindBy(id = "ctl00_MCPH_MainLogin_LoginButton")
WebElement loginButton;
public BookAHoliday logIn(String username, String password){
usernameInput.sendKeys(username);
passwordInput.sendKeys(password);
loginButton.click();
return PageFactory.initElements(driver, BookAHoliday.class);
}
}
As there is no test case written in the above code snippet, firefox driver will get opened in the #BeforeClass and as the condition driver != null is satisfied in #AfterClass, firefox is getting closed. This is expected behavior, as per your code.
Add Thread.sleep(3000); before driver.quit();or remove driver.quit();and see what happens. As you are not doing much in your test, it may be behaving correctly.
I was facing a similar problem. Firefox would open and then close without even navigating to the specified URL. Upgrade to the latest selenium(2.53) fixed the problem.
There was another instance where even the upgraded did not work. This was due to some plugins that my organization had installed.
Temporarily rename the "distribution" directory that is present in the location where Firefox is installed, and see if this works. Ex: C:\Program Files (x86)\Mozilla Firefox\ or /usr/lib/firefox/ This worked for me.

Categories

Resources