Not able to get data when NEXT is clicked in Java Selenium - java

Here is my code:
package working;
import java.util.List;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Test {
private static WebDriver driver;
public static void main(String[] args) throws Exception {
openBrowser();
System.out.println(scrape());
closeBrowser();
}
private static String table = "(//table[contains(#class,'datatable')])[1]";
private static String tr = table + "/tbody/tr";
private final static String next = table + "/preceding::a[text()='Next'][1]";
private final static String yesGotIt = "//body/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-banner \")]/div/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-button-wrapper \")]/button";
private static String scrape() throws Exception {
WebElement table_element = driver.findElement(By.xpath(table));
List<WebElement> tr_collection = table_element.findElements(By.xpath(tr));
int count = 1;
String rows = "";
driver.findElement(By.xpath(yesGotIt)).click();
while(count <= 3) {
for (WebElement trElement : tr_collection) {
List<WebElement> td_collection = trElement.findElements(By.xpath("td"));
for (WebElement tdElement : td_collection) {
rows += tdElement.getText() + "\t";
}
rows = rows + "\n";
}
System.out.println(rows);
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(next)));
driver.findElement(By.xpath(next)).click();
count += driver.findElements(By.xpath(next)).size();
System.out.println(count);
}
return rows;
}
private static void openBrowser() {
System.setProperty("webdriver.chrome.driver",
"E:\\eclipse-workspace\\src\\working\\selenium\\driver\\chromedriver.exe");
System.setProperty("webdriver.chrome.silentOutput", "true");
driver = new ChromeDriver();
driver.get("https://www.iata.org/en/publications/directories/code-search/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
private static void closeBrowser() {
driver.quit();
}
}
without while loop and next the code is working fine but when I run the aforementioned code its printing the first page table data 3 times repeatedly and throws the following error:
Mar 20, 2021 11:21:47 AM org.openqa.selenium.remote.ProtocolHandshake
createSession INFO: Detected dialect: OSS "Fly Armenia Airways"
Limited Liability Company Armenia VF 914 "NOVAIR" Limited Liability
Company Armenia NG 206 21 Air LLC UNITED STATES OF AMERICA 2I* 681
40-Mile Air, Ltd. UNITED STATES OF AMERICA Q5* 748 Air
Services Kenya H4* 874 874
2 "Fly Armenia Airways" Limited Liability Company Armenia VF 914
"NOVAIR" Limited Liability Company Armenia NG 206 21 Air LLC UNITED
STATES OF AMERICA 2I* 681 40-Mile Air, Ltd. UNITED STATES OF
AMERICA Q5* 748 Air Services Kenya H4* 874 874 "Fly Armenia
Airways" Limited Liability Company Armenia VF 914 "NOVAIR" Limited
Liability Company Armenia NG 206 21 Air LLC UNITED STATES OF
AMERICA 2I* 681 40-Mile Air, Ltd. UNITED STATES OF AMERICA Q5*
748 Air Services Kenya H4* 874 874
3 Exception in thread "main"
org.openqa.selenium.StaleElementReferenceException: stale element
reference: element is not attached to the page document (Session
info: chrome=89.0.4389.90) (Driver info: chromedriver=2.42.591088
(7b2b2dca23cca0862f674758c9a3933e685c27d5),platform=Windows NT
10.0.18363 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds For
documentation on this error, please visit:
https://www.seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.141.59', revision: 'e82be7d358', time:
'2018-11-14T08:25:53' System info: host: 'DESKTOP-832OS5B', ip:
'10.122.250.5', os.name: 'Windows 10', os.arch: 'amd64', os.version:
'10.0', java.version: '15.0.2' Driver info:
org.openqa.selenium.chrome.ChromeDriver Capabilities
{acceptInsecureCerts: false, acceptSslCerts: false,
applicationCacheEnabled: false, browserConnectionEnabled: false,
browserName: chrome, chrome: {chromedriverVersion: 2.42.591088
(7b2b2dca23cca0..., userDataDir: C:\Users\Windows\AppData\Lo...},
cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions:
{debuggerAddress: localhost:59261}, handlesAlerts: true,
hasTouchScreen: false, javascriptEnabled: true,
locationContextEnabled: true, mobileEmulationEnabled: false,
nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy:
normal, platform: XP, platformName: XP, rotatable: false,
setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true,
unexpectedAlertBehaviour: , unhandledPromptBehavior: , version:
89.0.4389.90, webStorageEnabled: true} Session ID: 5064d7cddc475396a421aa6d1639fb5c at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method) at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
at
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at
org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
at
org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
at
org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
at
org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
at
org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
at
org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at
org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at
org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:285)
at
org.openqa.selenium.remote.RemoteWebElement.getText(RemoteWebElement.java:166)
at working.Test.scrape(Test.java:41) at
working.Test.main(Test.java:21)
How can I print each page table data by clicking NEXT button?
Best regards

Refresh page after clicking Next button each time.
Declare table_element, tr_collection inside while.
Declare scrape() with void return and just call scrape() without print.
Also did some other changes in code.
import java.util.List;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Test
{
private static WebDriver driver;
public static void main(String[] args) throws Exception
{
openBrowser();
//System.out.println(scrape());
scrape();
closeBrowser();
}
private static String table = "(//table[contains(#class,'datatable')])[1]";
private static String tr = table + "/tbody/tr";
private final static String next = table + "/preceding::a[text()='Next'][1]";
private final static String yesGotIt = "//body/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-banner \")]/div/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-button-wrapper \")]/button";
private static void scrape() throws Exception
{
// WebElement table_element = driver.findElement(By.xpath(table));
// List<WebElement> tr_collection = table_element.findElements(By.xpath(tr));
int count = 1;
// String rows = "";
driver.findElement(By.xpath(yesGotIt)).click();
while (count <= 3) {
//Declare rows here - previous page's data will not repeatedly print
String rows = "";
System.out.println(count);
// Declare WebElement, List here
WebElement table_element = driver.findElement(By.xpath(table));
List<WebElement> tr_collection = table_element.findElements(By.xpath(tr));
for (WebElement trElement : tr_collection)
{
List<WebElement> td_collection = trElement.findElements(By.xpath("td"));
for (WebElement tdElement : td_collection)
{
rows += tdElement.getText() + "\t";
}
rows = rows + "\n";
}
System.out.println(rows);
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(next)));
driver.findElement(By.xpath(next)).click();
count += driver.findElements(By.xpath(next)).size();
//System.out.println(count);
//refresh page to ignore StaleElementReferenceException
driver.navigate().refresh();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(next)));
}
}
private static void openBrowser()
{
System.setProperty("webdriver.chrome.driver",
"E:\\eclipse-workspace\\src\\working\\selenium\\driver\\chromedriver.exe");
System.setProperty("webdriver.chrome.silentOutput", "true");
driver = new ChromeDriver();
driver.get("https://www.iata.org/en/publications/directories/code-search/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
private static void closeBrowser()
{
driver.quit();
}
}

Hope so everything is still working after changing table variable - look at console print. As visibility is focused on first table, last table's page change is not observeable. To focus on actual table's next button JavascriptExecutor is used and updated the whole code.
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Test
{
private static WebDriver driver;
public static void main(String[] args) throws Exception
{
openBrowser();
//System.out.println(scrape());
scrape();
//closeBrowser();
}
//private static String table = "(//table[contains(#class,'datatable')])[1]";
private static String table = "(//table[contains(#class,'datatable')])[last()]";
private static String tr = table + "/tbody/tr";
private final static String next = table + "/preceding::a[text()='Next'][1]";
private final static String yesGotIt = "//body/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-banner \")]/div/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-button-wrapper \")]/button";
private static void scrape() throws Exception
{
// WebElement table_element = driver.findElement(By.xpath(table));
// List<WebElement> tr_collection = table_element.findElements(By.xpath(tr));
int count = 1;
// String rows = "";
driver.findElement(By.xpath(yesGotIt)).click();
while (count <= 3) {
//Declare rows here - previous page's data will not repeatedly print
String rows = "";
System.out.println(count);
// Declare WebElement, List here
WebElement table_element = driver.findElement(By.xpath(table));
List<WebElement> tr_collection = table_element.findElements(By.xpath(tr));
for (WebElement trElement : tr_collection)
{
List<WebElement> td_collection = trElement.findElements(By.xpath("td"));
for (WebElement tdElement : td_collection)
{
rows += tdElement.getText() + "\t";
}
rows = rows + "\n";
}
System.out.println(rows);
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(next)));
//scroll to next button
JavascriptExecutor je = (JavascriptExecutor) driver;
WebElement we = driver.findElement(By.xpath(next));
je.executeScript("arguments[0].scrollIntoView(true);", we);
we.click();
driver.findElement(By.xpath(next)).click();
count += driver.findElements(By.xpath(next)).size();
//System.out.println(count);
//refresh page to ignore StaleElementReferenceException
driver.navigate().refresh();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(next)));
}
}
private static void openBrowser()
{
System.setProperty("webdriver.chrome.driver",
"E:\\eclipse-workspace\\src\\working\\selenium\\driver\\chromedriver.exe");
System.setProperty("webdriver.chrome.silentOutput", "true");
driver = new ChromeDriver();
driver.get("https://www.iata.org/en/publications/directories/code-search/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
private static void closeBrowser()
{
driver.quit();
}
}

Related

All though Xpath is showing all elements in selector hub from expected div ,selenium isn't capturing completely

I want to capture all the headers of a table using the selenium using the. I am using the
Xpath to capture the webelement using Xpath.
Xpath:
"//div[#class='dataTables_scrollHeadInner']//tr[#id='report-data-table-header-0']/th"
and it shows all the elements of the div i.e (9 th's),but when I capture it using selenium I only get 7 elements.
All the xpaths are mentioned are required the and the commented block of code is function call of homePage.view_report_values(textString).
Source Code:
package Onsight.Framework;
import java.util.ArrayList;
import java.util.List;
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 com.github.javafaker.Faker;
import avdhut.onsight.commonutils.BaseComponenets;
import avdhut.onsight.pageobject.HomePage;
import avdhut.onsight.pageobject.LoginPage;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Webtable {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
String urlString = "https://oinsightsvm1.westindia.cloudapp.azure.com:444/ctsOInsightsBMS/res/createReport.html";
String userEmailString = "User66";
String userPassword = "Avdhut#5201";
String titleString;
String textString="Clarita";
Faker faker = new Faker();
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
// options.addArguments("--ignore-ssl- errors=yes");
options.addArguments("--ignore-certificate-errors");
WebDriver driver = new ChromeDriver(options);
driver.get(urlString);
LoginPage loginPage = new LoginPage(driver);
loginPage.login_username(userEmailString);
loginPage.click0nsubmit();
loginPage.EnterPassword(userPassword);
loginPage.click0nsubmit();
HomePage homePage = new HomePage(driver);
homePage.view_report_values(textString);
}
}
//tr[class='odd'] em[class='fa fa-table']
Page Object file:
[![public class HomePage extends BaseComponenets {
WebDriver driver;
By createReportBy=By.cssSelector("button\[data-target*='#addReportModal'\]");
By baseTableBy=By.xpath("//table\[#id='query-table'\]");
By report_name_rowsBy=By.xpath("//tbody/tr");
By viewBy=By.xpath("//button\[contains(#title,'View')\]");
By view_dataBy=By.xpath("//button\[contains(#title,'View data')\]");
By dataBy=By.xpath("//table\[#id='reportDataTable-0'\]/tbody/tr ");
By teable_headingBy=By.xpath("//div\[#class='dataTables_scrollHeadInner'\]//tr\[#id='report-data-table-header-0'\]/th");
By next_paginateBy=By.xpath("//li\[#id='reportDataTable-0_next'\]");
By paginateBy=By.xpath("//div\[#id='reportDataTable-0_paginate'\]/ul\[#class='pagination'\]/li\[#class='paginate_button page-item '\]");
By no_of_pagesBy=By.xpath("//div\[#id='reportDataTable-0_info'\]");
public HomePage(WebDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
this.driver=driver;
}
public void CreateReport_Button() {
IsClickable(createReportBy);
WebElement create_Report=driver.findElement(createReportBy);
create_Report.click();
}
public void get_headers() {
IsVisible(teable_headingBy);
List<WebElement> table_headerElement=driver.findElements(teable_headingBy);
for (WebElement header : table_headerElement) {
System.out.println(header.getText());
}
}
public void view_report_values(String report_title) throws InterruptedException {
IsVisible(baseTableBy);
WebElement baseTable=driver.findElement(baseTableBy);
List<WebElement> table_roWebElement=baseTable.findElements(report_name_rowsBy);
List<String> list=new ArrayList<String>();
for (WebElement webElement : table_roWebElement) {
if (webElement.getText().contains(report_title)) {
System.out.println(true);
IsClickable(viewBy);
System.out.println(webElement.getText());
webElement.findElement(viewBy).click();
IsClickable(view_dataBy);
driver.findElement(view_dataBy).click();
IsVisible(next_paginateBy);
List<WebElement> pagebar=driver.findElements(paginateBy);
for(WebElement page:pagebar) {
list.add(page.getText());
}
// name(list);
if (driver.findElement(next_paginateBy).isDisplayed()) {
for (int i = 1; i <= 30; i++) {
if (i==1) {
System.out.println("first_page");
get_headers();
}
// Thread.sleep(10000);
}
} else {
}
//
}
}][1]][1]
Console O/P:
TIMESTAMP
SOURCE NAME
SOURCE STATE
ACK STATE
MESSAGE TEXT
LAST NOTES
After that I googled and then found some articles and then In order to test I used console of google chrome
document.getElementsByClassName('dataTables_scrollBody').scrollLeft += 250", "
It gave me an error , then, I used:
document.getElementsByClassName('dataTables_scrollBody').scrollLeft +=250
Then,
I got the message :
NaN
This is the table I want to scroll also the classname mentioned in belongs to same div of the table in image
After login, add the below code and try:
driver.findElement(By.xpath(".//button[#class='toast-close-button']")).click();
driver.findElement(By.xpath("(.//td[text()='random']//parent::tr//td/button)[1]")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("(.//div[#class='modal-content']//button[#type='button' and #title='View data'])[1]")).click();
Thread.sleep(2000);
JavascriptExecutor js=(JavascriptExecutor)driver;
List<WebElement> headers = driver.findElements(By.xpath(".//div[#class='dataTables_scrollHead']//th"));
System.out.println("Total no. of headers: " + headers.size());
System.out.println("Headers: ");
System.err.println("========");
for (WebElement header : headers) {
js.executeScript("arguments[0].scrollIntoView(true);", header);
System.out.println(header.getText());
}
Output:
Total no. of headers: 9
Headers:
========
TIMESTAMP
SOURCE NAME
SOURCE STATE
ACK STATE
MESSAGE TEXT
LAST NOTES
ALL NOTES
ALARM VALUE
LOW LIMIT
I answered your previous question also, check that, if it works for you, mark that as answer.

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.

Selenium cant access a hidden element

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

Could not click on dropdown in Safari browser on MacBook Pro

I am new to automation and trying to click on a dropdown in my application in Safari Browser but the script fails with error.
Please Help.
Error :
An unknown server-side error occurred while processing the command. (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DHRODCLPC0316', ip: '2409:4042:2098:9614:d857:22cd:8ec8:8ceb%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.13.6', java.version: '13.0.2'
Driver info: org.openqa.selenium.safari.SafariDriver
Capabilities {applicationCacheEnabled: true, browserName: safari, cleanSession: true, cssSelectorsEnabled: true, databaseEnabled: true, handlesAlerts: true, javascriptEnabled: true, locationContextEnabled: false, nativeEvents: true, platform: MAC, platformName: MAC, rotatable: false, version: 13605.3.8, webStorageEnabled: true}
Session ID: C7B2C752-80D4-4453-B0C7-C35151B11F3C
Configuration :
Safari Version 13
Macbook Pro machine
Flow of Code
Open URL https://shop-lbs.mediatis.de
Login with credentials
Click on Quick order
Enter few codes to add in cart
Verify prices and checkout
Now select shipping address from dropdown
SCRIPT :
package lbs.leica;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Testcase_240_UAT_SAFARI extends ExtentReport_UAT
{
WebDriver driver;
public static String cardNumber = "4111-1111-1111-1111";
public static String Expiry = "01/29";
#BeforeTest
public void initialization()
{
test = extent.createTest("Order tests in UAT plethora of different order tests to verify tax, shipping, customer pricing, list pricing");
driver = new SafariDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.navigate().to("https://shop-lbs.mediatis.de");
System.out.println(driver.getTitle());
reportLog(driver.getTitle());
}
#Test
public void VerifyPrices() throws IOException, InterruptedException
{
driver.findElement(By.xpath("//*[#id='login-menu_login_title']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("(//*[#id='ShopLoginForm_Login'])[2]")).clear();
driver.findElement(By.xpath("(//*[#id='ShopLoginForm_Login'])[2]")).sendKeys("fjsim#buffalo.edu");
Thread.sleep(2000);
driver.findElement(By.xpath("(//*[#id='ShopLoginForm_Password'])[2]")).sendKeys("!InterShop00!");
reportLog("Entered username and password");
// Click on login in button
driver.findElement(By.xpath("(//*[#class='account-sign-in btn btn-primary'])[2]")).click();
Thread.sleep(5000);
reportLog("Clicked on Login ");
driver.findElement(By.xpath("//*[#class='view-account']")).click();
Thread.sleep(5000);
// Click on Quick Order
driver.findElement(By.xpath("//*[#class='quickorder-li hidden-xs']")).click();
Thread.sleep(5000);
reportLog("Clicked on Quick Order ");
// Click on Copy and paste
driver.findElement(By.xpath("(//*[text()='Copy and paste'])[1]")).click();
Thread.sleep(4000);
reportLog("Clicked on Copy and paste ");
//Enter Codes in text box
String[] voucherCodes = {"DS9800 1", "PA0515 2", "AR0222 3", "PA0027 4", "PA0571 5", "PA0813 6", "3801800 1", "3803650 1", "3800680 1", "3801815 1", "3800675 1", "3800080 1", "3800050CL 1", "3800161 1"};
WebElement input = driver.findElement(By.id("addToCartCopyAndPaste_textArea"));
for (String voucher : voucherCodes)
{
input.sendKeys(voucher+"\n");
}
reportLog("Entered Codes ");
//Click on Add to cart
driver.findElement(By.id("addToCartCopyAndPaste")).click();
Thread.sleep(9000);
reportLog("Clicked on Add to cart ");
//Verify and Print price
List<WebElement> VerifyPrice = driver.findElements(By.xpath("//*[#class=' col-xs-4 col-sm-offset-1 col-sm-2 list-item column-price single-price']"));
for(WebElement price:VerifyPrice)
{
System.out.println(price.getText());
reportLog(price.getText());
}
System.out.println();
//Verify and Print Product
List<WebElement> VerifyProduct = driver.findElements(By.xpath("//*[#class='product-title']"));
for(WebElement product:VerifyProduct)
{
System.out.println(product.getText());
reportLog(product.getText());
}
System.out.println();
Thread.sleep(4000);
//Click Checkout on shopping cart page
driver.findElement(By.xpath("//*[#class='btn btn-block btn-primary']")).click();
Thread.sleep(4000);
reportLog("Clicked Checkout on shopping cart page ");
//Select shipping address
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollTo(0, 200)");
Thread.sleep(5000);
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//*[#class='btn dropdown-toggle btn-default'])[2]")));
System.out.println("Address dropdown visible");
WebElement e1 = driver.findElement(By.xpath("(//*[#class='btn dropdown-toggle btn-default'])[2]"));
e1.click();
Thread.sleep(5000);
System.out.println("Address dropdown Clicked");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//*[#class='dropdown-menu inner'])[2]/li[1]")));
System.out.println(" dropdown visible");
driver.findElement(By.xpath("(//*[#class='dropdown-menu inner'])[2]/li[1]")).click();
Thread.sleep(2000);
System.out.println(" dropdown clicked");
reportLog("Selected first address ");
"An unknown server-side error occurred while processing the command."
This may indicate a bug in safaridriver. To more easily see what's going on, try passing 'safari:diagnose' capability to New Session. This will cause safaridriver to log protocol traffic to ~/Library/Logs/com.apple.WebDriver//. See man safaridriver for more information about enabling diagnostics.
If the protocol trace shows a command is failing unexpectedly (eg, HTTP 500), then please file an issue at https://feedbackassistant.apple.com/ so that it may be investigated by Apple. Including a reduced, standalone test case is super helpful for fixing issues, so please do that!
Thanks!

Why do I get 1001 error every time I try to login into Naukari.com using my selenium test script?

Naukari error img: I am getting This error on naukari page but on doing manually it does not appear
I am trying to automate Naukari.com so that it gets updated daily on its own instead of me visiting the website daily to do it. My script is as follows:
package naukariUpdate;
import java.util.Set;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import naukariLoginPOM.LoginPOM;
public class NaukariUpdater {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","./driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.naukri.com/");
driver.getTitle();
String mainWindowTitle = driver.getTitle();
String mainWindowID = driver.getWindowHandle();
Set<String> s = driver.getWindowHandles();
for (String handleID : s)
{
driver.switchTo().window(handleID);
System.out.println(driver.getTitle());
String windowID = driver.getTitle();
if (!windowID.equals(mainWindowTitle))
{
driver.close();
}
}
driver.switchTo().window(mainWindowID);
driver.findElement(By.xpath("(//div[text()='Login'])[1]")).click();
driver.findElement(By.xpath("//a[.='Google']")).click();
Set<String> window = driver.getWindowHandles();
System.out.println();
for (String handleID : window)
{
driver.switchTo().window(handleID);
String windowTitle = driver.getTitle();
System.out.println(windowTitle+"\t"+mainWindowTitle);
if (!windowTitle.equals(mainWindowTitle))
{
System.out.println("in IF");
driver.switchTo().window(handleID);
break;
}
}
System.out.println("out of switching "+driver.getTitle());
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement webElement = driver.findElement(By.xpath("//input[#id='identifierId']"));
wait.until(ExpectedConditions.visibilityOf(webElement));
LoginPOM POM = new LoginPOM(driver);
WebElement logIN = POM.getLogIn();
logIN.sendKeys("Sorry type in your own email ID bro");
WebElement nextBtn = POM.NextButton();
nextBtn.click();
wait.until(ExpectedConditions.visibilityOf(POM.getPassword()));
WebElement pswd = POM.getPassword();
pswd.sendKeys("Sorry type in your own password bro");
nextBtn.click();
}
}
This is the POM:
package naukariLoginPOM;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPOM {
public LoginPOM(WebDriver driver)
{
PageFactory.initElements(driver , this);
}
#FindBy(xpath = "//input[#id='identifierId']")
private WebElement LogIn;
public WebElement getLogIn()
{
return LogIn;
}
#FindBy(xpath = "//input[#type='password']")
private WebElement Pswd;
public WebElement getPassword()
{
return Pswd;
}
#FindBy(xpath = "//content[.='Next']")
private WebElement NextBtn;
public WebElement NextButton()
{
return NextBtn;
}
}
I don't get where I made the mistake. Everything seems to run fine, yet I get error 1001 in the end. This does not happen when I carry out the process manually by clicking and typing. How can I resolve it?
Error #1001 is an issue with adobe flash player. You will need to redeploy (reinstall) your adobe flash player as it either missing critical libraries or those libraries are corrupted. This is a documented error with Adobe. You can read more about the issue from this link here:
https://forums.adobe.com/thread/258374?start=0&tstart=0
Unfortunately, this is not an issue that is related to Selenium.
The solution is to reinstall your adobe flash player. If your permissions on your workstation are not high enough to do this, ask your IT team.

Categories

Resources