I need to open over 100 pages (https://same URL/"different page") and I want to use for loop with variable to open a certain amount of them at once.
I wrote below code in Java selenium but got an error: javascript error: missing ) after argument list
Could someone help me to figure out where went wrong please? Thank you.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
public class multibrowser {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"E:\\Selenium\\chromedriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.abc/";
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.location = \'" + url + "\'");
new Click().clickElement(driver.findElement(By.cssSelector("span[title=123']")));
try {
Thread.sleep(15000);
} catch (InterruptedException ie) {
System.out.println("Loading time longer than 15 seconds");
}
// create list
List<String> crunchifyList = new ArrayList<String>();
// add 2 different values to list
crunchifyList.add("123");
crunchifyList.add("456");
//For loop
for (int i = 0; i < crunchifyList.size(); i++) {
js.executeScript("window.open('https://www.abc/' + crunchifyList.get(i) +', '_blank');");
}
}
}
You missed quotes(""), should be:
js.executeScript("window.open('https://www.abc/'" + crunchifyList.get(i) + "', '_blank');");
Related
Here i am trying to select return date 12 of April month. i tried with different customized xpath and css but unable to locate the element:
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 Make_my_trip {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "F:\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.makemytrip.com/");
// Selecting Return date
driver.findElement(By.id("hp-widget__return")).click();
//WebDriverWait ws = new WebDriverWait(driver, 10);
//ws.until(ExpectedConditions.presenceOfElementLocated(By.id("dp1551508380301")));
Thread.sleep(2000);;
while (!driver.findElement(By.xpath("//span[#class ='ui-datepicker-month']")).getText().contains("April")) {
System.out.println("Return date selected ");
driver.findElement(By.xpath(
"div[#id='dp1551508898872']//span[#class='ui-icon ui-icon-circle-triangle-e'][contains(text(),'Next')"))
.click();
}
List<WebElement> returndate = driver.findElements(By.xpath("//a[#class ='ui-state-default']"));
int count = returndate.size();
for (int j = 0; j < count; j++) {
String returndatetext = driver.findElements(By.xpath("//a[#class ='ui-state-default']")).get(i).getText();
if (returndatetext.equalsIgnoreCase("12")) {
driver.findElements(By.xpath("//a[#class ='ui-state-default']")).get(i).click();
break;
}
}
}
PS :
If we use explicitly wait getting "org.openqa.selenium.InvalidSelectorException" Error so as of now use Thread.sleep(1000).
If we use Xpath //div[#class='ui-datepicker-group ui-datepicker-group-last']/div/a/span[contains(text(),'Next' )][1] getting
org.openqa.selenium.ElementNotVisibleException: element not visible
"Element not visible". I had this error too. It's mean your searchable element isn't visible in the current snapshot. You should focus on that element or scroll down till element appear in the snapshot
I want to separate my code in to smaller functions.
But had an issue as driver was not available to all functions.
So i declared it as a constant (or is there a better way of doing this ?)
but in 3rd function it is failing on line :
Select dropdown_finance_product = new Select(driver.findElement(By.xpath("//select[#id='ResultsNumber']")));
Here is the console message :
Exception in thread "main" java.lang.NullPointerException
at Scraping.scrapeit.fetch_urls(scrapeit.java:49)
at Scraping.scrapeit.main(scrapeit.java:24)
Code :
package Scraping;
import java.io.IOException;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import tools.Xls_Reader;
public class scrapeit {
static WebDriver driver;
public static void main(String[] args) throws IOException {
start_browser();
fetch_urls();
read_excel();
}
public static void start_browser() {
System.setProperty("webdriver.chrome.driver", "C:\\Chrome Driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.get("http://www.example.com/search/items/new/");
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.titleContains("New items));
}
public static void fetch_urls() {
Select dropdown_finance_product = new Select(driver.findElement(By.xpath("//select[#id='ResultsNumber']")));
dropdown_finance_product.selectByVisibleText("100");
System.out.println("Selected 100 Items Dropdown");
// Open Excel and write urls back
Xls_Reader datatable = new Xls_Reader("C:\\scrape.xlsx");
List<WebElement> num_items = driver.findElements(
By.xpath("//a [contains(#href,'http://www.example.com/search/items/new/latest-')] "));
for (int i = 0; i < num_items.size(); i++) {
System.out.println("How many items on page = : " + num_items.size() + " counter = " + i);
String link = num_items.get(i).getAttribute("href");
datatable.setCellData("New", "URL", i + 2, link);
System.out.println("URL : " + link);
}
}
public static void read_excel() {
// Read in url and process...
Xls_Reader datatable = new Xls_Reader("C:\\scrape.xlsx");
int r = datatable.getRowCount("URL");
int c = datatable.getColumnCount("URL");
System.out.println("num of rows = " + r + " num of cols = " + c);
}
}
The error says it all :
Exception in thread "main" java.lang.NullPointerException
In class scrapeit you have already declared webdriver as an instance of WebDriver as static as follows :
static WebDriver driver;
But then you are again initializing another driver as a new instance of WebDriver as follows :
WebDriver driver = new ChromeDriver();
Hence you see java.lang.NullPointerException
Solution
A quick solution will instead of creating another instance of the WebDriver you need to use the static instance of WebDriver. So you need to remove WebDriver from WebDriver driver = new ChromeDriver(); as follows :
driver = new ChromeDriver();
This is the code which I am using. I want to select different values from the "class" drop down. I am getting the count of the no. of drop downs as correct but the values are not getting selected under the dropdown.
package selectclasspackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.junit.Test;
//import org.junit.Before;
import static javax.swing.JOptionPane.showMessageDialog;
import java.util.List;
import org.openqa.selenium.WebElement;
public class selectclass {
#Test
public void Sample () throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "C:\\\\Users\\Rajiv\\Downloads\\geckodriver-v0.14.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver ();
String URL = "https://www.goibibo.com/";
driver.get(URL);
driver.manage().window().maximize();
Thread.sleep(3000);
Select seatingclass = new Select (driver.findElement(By.id("gi_class")));
List <WebElement> elementCount = seatingclass.getOptions();
System.out.println(elementCount.size());
seatingclass.selectByVisibleText ("Premium Economy");
System.out.println("Premium Economy selected");
Thread.sleep(3000);
for (int i = 0; i < elementCount.size(); i++)
{
new Select(driver.findElement(By.id("gi_class"))).selectByIndex(i);
}
seatingclass.selectByIndex(2);
System.out.println("First Class selected");
Thread.sleep(3000);
seatingclass.selectByValue("B");
System.out.println("Business Class selected");
Thread.sleep(3000);
}
}
Why are you using for loop? selectByValue works fine as the number of options in #selnoOfAdults are fixed. The below code worked fine. It selected 10 in the #selnoOfAdults.
Select seatingclass = new Select(driver.findElement(By.id("selnoOfAdults")));
seatingclass.selectByValue("10");
I'm trying to get the link name of all the links present on a particular page, but some link get visible after hovering over a particular link, like there is a parent child relation between those links and Selenium WebDriver is unable to identify the link names for the child link.
Is there any possible way to get all the link names including the parent and the child?
package test;
import static org.junit.Assert.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;
import mx4j.tools.remote.http.HTTPConnectionManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class SparshLink {
WebDriver driver;
#Before
public void setUp() throws Exception {
String basePath = System.getProperty("user.dir");
String finalPath = basePath + "\\IEDriver\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", finalPath);
driver = new InternetExplorerDriver();
driver.navigate().to("http://sparshv2/");
}
#After
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void test() throws Exception {
List<WebElement> list;
list = driver.findElements(By.tagName("a"));
System.out.println("Number of links : " + list.size());
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
for (int i = 0; i < list.size(); i++) {
System.out.println(i);
URL url = new URL(list.get(i).getAttribute("href"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() != 404) {
System.out.println(list.get(i).getText() + "is working properly.");
} else {
System.out.println(list.get(i).getText() + "is not working properly.");
}
connection.disconnect();
}
}
}
I'm sorry i wont be able to share the code behind the application.
'a' will be the tag but I believe all your URL should be there in href attribute.
You should refer below:-
Finding all "A" tags with specific strings in the attribute href?
I was trying to run Sikuli WebDriver based tests on Sauce On Demand infrastructure.
But I have a problem with RemoteWebDriver.
I have this BaseSikuliWebDriver class
package com.pitito.sikuli.base;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import com.pitito.core.basetests.BaseLoggingTest;
import com.pitito.selenium.webdriver.RemoteWebDriverSession;
import com.pitito.selenium.webdriver.WebDriverScreenshooter;
import com.pitito.sikuli.webdriver.SikuliFirefoxDriver;
/**
* Base class for all Sikuli WebDriver tests.
*
* #author guillem.hernandez
*/
public abstract class BaseSikuliWebDriverTest {
Map<String, Object> sauceJob = new HashMap<String, Object>();
private static SikuliFirefoxDriver sikuliDriver;
protected SikuliFirefoxDriver driver() {
return getDriver();
}
public static SikuliFirefoxDriver getDriver() {
return sikuliDriver;
}
public static void setDriver(SikuliFirefoxDriver driver) {
BaseSikuliWebDriverTest.sikuliDriver = driver;
}
#Override
#BeforeMethod(alwaysRun = true)
protected void setup(Method method, Object[] testArguments) {
super.setup(method, testArguments);
String sessionId = method.getName() + "_" + testArguments.hashCode();
DesiredCapabilities caps = DesiredCapabilities.firefox();
caps.setCapability("id", sessionId);
caps.setCapability("name", sessionId);
caps.setCapability(CapabilityType.BROWSER_NAME, "firefox");
caps.setCapability("platform", Platform.XP);
caps.setCapability("version", "21");
try {
sikuliDriver = (SikuliFirefoxDriver) new Augmenter().augment(new RemoteWebDriver(new URL("http://"
+ RemoteWebDriverSession.USER + ":" + RemoteWebDriverSession.APIKEY
+ "#ondemand.saucelabs.com:80/wd/hub"), caps));
} catch (MalformedURLException e) {
e.printStackTrace();
}
setDriver(sikuliDriver);
}
#Override
#AfterMethod(alwaysRun = true)
protected void teardown(ITestResult tr, Method method) {
if ((logger() != null) && (tr.getStatus() == ITestResult.FAILURE)) {
logUnexpectedException(tr.getThrowable());
}
super.teardown(tr, method);
sikuliDriver.quit();
}
#Override
protected void logScreenshot(String screenshotName) {
logResource(new WebDriverScreenshooter(driver(), screenshotName).getScreenshot());
}
}
The test I implemented is the Sikuli WebDriver example and the code is as follows:
package com.pitito.sikuli.tests;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
import com.pitito.sikuli.base.BaseSikuliWebDriverTest;
import com.pitito.sikuli.webdriver.ImageElement;
/**
* Sikuli Firefox WebDriver Automated Test Example.
*
* #author guillem.hernandez
*/
public class SikuliGoogleCodeTest extends BaseSikuliWebDriverTest {
#Test(groups = { "ES" }, description = "Use Sikuli to search on Google Maps")
public void testSikuliWebDriverPassingExample_ES() {
verifySikuliWebDriverPassingTest();
}
private void verifySikuliWebDriverPassingTest() {
// visit Google Map
driver().get("https://maps.google.com/");
// enter "Denver, CO" as search terms
WebElement input = driver().findElement(By.id("gbqfq"));
input.sendKeys("Denver, CO");
input.sendKeys(Keys.ENTER);
ImageElement image;
// find and click on the image of the lakewood area
try {
image = driver().findImageElement(new URL("https://dl.dropbox.com/u/5104407/lakewood.png"));
image.doubleClick();
// find and click on the image of the kendrick lake area
image =
driver().findImageElement(new URL("https://dl.dropbox.com/u/5104407/kendrick_lake.png"));
image.doubleClick();
// find and click the Satellite icon to switch to the satellite view
image = driver().findImageElement(new URL("https://dl.dropbox.com/u/5104407/satellite.png"));
image.click();
// find and click the plus button to zoom in
image = driver().findImageElement(new URL("https://dl.dropbox.com/u/5104407/plus.png"));
image.click();
// find and click the link button
WebElement linkButton = driver().findElement(By.id("link"));
linkButton.click();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
When I try to run the test, the error I get is this one:
[Invoker 18958118] Invoking #BeforeMethod BaseSikuliWebDriverTest.setup(java.lang.reflect.Method, [Ljava.lang.Object;)[pri:0, instance:com.pitito.sikuli.tests.SikuliGoogleCodeTest#137008a]
Failed to invoke configuration method com.pitito.sikuli.base.BaseSikuliWebDriverTest.setup:org.openqa.selenium.remote.RemoteWebDriver$$EnhancerByCGLIB$$52a1cf6f cannot be cast to com.pitito.sikuli.webdriver.SikuliFirefoxDriver
The problem resides here:
sikuliDriver = (SikuliFirefoxDriver) new Augmenter().augment(new RemoteWebDriver(new URL("http://"
+ RemoteWebDriverSession.USER + ":" + RemoteWebDriverSession.APIKEY
+ "#ondemand.saucelabs.com:80/wd/hub"), caps));
How can I use SikuliFirefoxDriver remotely? How can I cast RemoteWebDriver with SikuliFirefoxDriver? Can I do it?
As far as I know, the Selenium Grid server does not have the capability of passing Sikuli commands (and binary screenshots for comparison purposes) through its JSON api. Not even SauceLabs has this capability. Hopefully, its on the radar to be implemented someday. On the SauceLabs forum, there is someone that asked this question (and I answered that one also with this same answer).
I know that there is a project in-progress called Marionette that is supposed to be able to automate browser/Firefox menus and native dialogs.
I implemented a remote driver version of sikuli driver. You can use that to do this action.
Please feel free to fork:
https://github.com/AJ-72/SikuliRemoteWebdriver
My guess is that SikuliFirefoxDriver cannot be augmented because it was not invoked as RemoteWebdriver. Try invoke it as Remote webdriver with sikuli as desired capabilities.
Please, post here if it worked (I could not find proofs if it is possible, but still worth a shot)