i need to access a website multiple times a day and want to skip the Log-In page. This is why i want to use Cookies in Java Selenium Chromedriver, for skipping that Log-In after accessing it the first time on a day.
Selenium is saving the Cookies correctly, but does not use them and i dont get access on the following page. Can you help me?
This is my Code:
public static void main(String[] args) throws InterruptedException {
Set<Cookie> cookie = null;
Iterator<Cookie> itr = null;
while (true) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Maxi\\Desktop\\ChromeDriver.exe");
driver = new ChromeDriver();
driver.get("https://www.xxxxxx.xxx");
while (itr != null && itr.hasNext()) {
driver.manage().addCookie(itr.next());
}
driver.navigate().refresh();
WebDriverWait wait0 = new WebDriverWait(driver, 20);
if (itr == null) {
String UserID = "LoginFieldXpath";
wait0.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(UserID)));
driver.findElement(By.xpath(UserID)).sendKeys("Username");
String PW = "PasswordField Xpath";
driver.findElement(By.xpath(PW)).sendKeys("Password");
String LogIn = "LoginButtonXpath";
driver.findElement(By.xpath(LogIn)).click();
cookie = driver.manage().getCookies();
itr = cookie.iterator();
}
}
}
You can create user profile in Chrome like this
options:
addArguments("user-data-dir="+"path_to_empty_folder");
Then make sign up, so cookie will be stored in this profile. And than just copy this user data dir to another folder
FileUtils.copyDirectory(new File("path-to-dir-with-cookie"), new File("new-dir"));
options.addArguments("user-data-dir="+"new-dir");
Selenium starts a new temporary browser instance each time, so it doesn't come with any cookies stored, cache or anything like that.
I would suggest moving your open chrome driver to be outside of the while loop so you'll be able to reuse it each time you want to check a page. Maybe either move the login outside of the loop as well or check if you need to log in. Then just grab whatever page you're trying to check inside the loop each time you need to.
public static void main(String[] args) throws InterruptedException {
Set<Cookie> cookie = null;
Iterator<Cookie> itr = null;
// move this outside the loop
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Maxi\\Desktop\\ChromeDriver.exe");
driver = new ChromeDriver();
while (true) {
driver.get("https://www.xxxxxx.xxx");
// not sure why you're adding a cookie?
// it should automatically accept page cookies that are set
while (itr != null && itr.hasNext()) {
driver.manage().addCookie(itr.next());
}
driver.navigate().refresh();
WebDriverWait wait0 = new WebDriverWait(driver, 20);
// check to make sure that you need to log in
if (itr == null) {
String UserID = "LoginFieldXpath";
wait0.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(UserID)));
driver.findElement(By.xpath(UserID)).sendKeys("Username");
String PW = "PasswordField Xpath";
driver.findElement(By.xpath(PW)).sendKeys("Password");
String LogIn = "LoginButtonXpath";
driver.findElement(By.xpath(LogIn)).click();
cookie = driver.manage().getCookies();
itr = cookie.iterator();
}
}
}
Related
I am trying to learn java and selenium by myself and creating a robot that will scan job/career pages for certain string (job name e.g. QA , developer...)
I'm trying to create JAVA code using selenium, that will read URL links from CSV file and open a new tab.
the main goal is to add several url in the CSV and assert/locate a certain string in the designated url's for example: is there "Careers" link in each URL, the test will pass for this specific url.
created a selenium project
created new chromeDriver
Created CSV built from 3 columns (ID, company's name, URL) - and added it to the project
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class URLSearch {
public static void main(String[] args) {
ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();
String fileName = "JobURLList.csv";
File file = new File(fileName); //read from file
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String data = inputStream.next();
System.out.println(data);
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
first line in the CSV - titles: id, name, url
Read the url from the second line - e.g. https://careers.google.com/jobs/"
open browsertab and start going over the url list (from the CSV)
locate a hardcoded string (e.g. "developer" , "qa" ..) in each url
if such a string was found, write in console the url that the test turned out to be positive (such a string was found in one of the url's).
if no such string was found, skip to the next url.
To open the new tab do something like this (this assumes "driver" object is your WebDriver):
((JavascriptExecutor)driver).executeScript("window.open('about:blank', '_blank');");
Set<String> tab_handles = driver.getWindowHandles();
int number_of_tabs = tab_handles.size();
int new_tab_index = number_of_tabs-1;
driver.switchTo().window(tab_handles.toArray()[new_tab_index].toString());
You could then create a function that takes a list of key/value pairs, with URL and term to search for and loop through it. Do you want to use a hashmap for this, or maybe an ArrayList of a class (id/name/url)? The code for finding the text would be something like this (assumes you've defined a var of "Pass" to boolean):
driver.get([var for URL]);
//driver will wait for pageready state, so you may
// not need the webdriver wait used below. Depends
// on if the page populates data after pagereadystate
String xpather = "//*[contains(text(), '" + [string var for text to search for] + "')]";
try
{
wait = new WebDriverWait(driver, 10);
List<WebElement> element = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath(xpather)));
this.Pass = false;
if (element.size() > 0)
{
this.Pass = true;
}
}
catch (Exception ex)
{
this.Pass = false;
System.out.println ("Exception finding text: " + ex.toString());
}
Then logic for if (this.Pass==true or false)..
I already created a method to get the transaction ID but the element cannot be located. I cannot retrieve the ID in the web table because it shows an error that unable to locate the element. Besides, it will open another blank window.
This is the method to get the ID
public String getTransactionID(String ID) throws IOException {
File src = new File("C:\\selenium\\ExcelData\\TestData.xlsx");
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
XSSFSheet sh1 = wb.getSheetAt(0);
String getValue = null;
String TransactionID = null;
for (int i = 0; i<=1000; i++) {
if(sh1.getRow(i).getCell(0) != null)
{
getValue = sh1.getRow(i).getCell(0).getStringCellValue();
}
if(getValue != null) {
if(getValue.contains(ID)) {
System.setProperty("webdriver.gecko.driver","C:\\selenium\\geckodriver-v0.23.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
TransactionID = driver.findElement(By.xpath("//table/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[1]/td")).getText();
FileOutputStream fout = new FileOutputStream(src);
sh1.getRow(i).createCell(1).setCellValue(TransactionID);
wb.write(fout);
fout.close();
break;
}
}
}
return TransactionID;
This is the line to call the method
GetExcel transID = new GetExcel();
transID.getTransactionID("Transaction ID");
Issue
The issue lies in the below snippet:
WebDriver driver = new FirefoxDriver();
The will open up a new Firefox browser. That's why you saw a 'blank window' open up.
TransactionID = driver.findElement(By.xpath("//table/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[1]/td")).getText();
Immediately after that you're attempting to search for the element on the website. As you can imagine, attempting to find an element on a blank page will obviously throw you an error.
You need to navigate to the website first:
driver.get(your_url_here);
Sidenotes
Your xpath isn't ideal as it is too hardcoded -- if a new element is created in the website, your xpath will probably break. You should instead use a more dynamic approach that utilizes the element's DOM properties such as id:
//table[#id='xxx']//td
Documentation: https://www.w3schools.com/xml/xml_xpath.asp
In addition, your variable name TransactionID should be in lower caps, i.e. transactionID.
I am trying to handle multiple browser windows using selenium webdriver, but getting java.util.NoSuchElementException. A week ago this code was working fine but now getting issue in the code while trying to switch to third window.
The issue I am getting on line String Third_window = iterate.next();
Note: This code was working fine properly a week ago.
public class Firefox {
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\singhais\\Documents\\Selenium Prerequisites\\geckodriver.exe");
driver = new FirefoxDriver();
driver.get("https://www.hdfcbank.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// First window
System.out.println("GettingID for first Window");
Set<String> win = driver.getWindowHandles();
Iterator<String> iterate = win.iterator();
String first_window = iterate.next();
System.out.println(first_window);
driver.findElement(By.xpath("//*[#id='element2']/div[1]/div[3]/div[2]/a/img")).click();
// second window
System.out.println("GettingID for second Window");
win = driver.getWindowHandles();
iterate = win.iterator();
first_window = iterate.next();
System.out.println(first_window);
System.out.println(driver.getTitle());
String second_window = iterate.next();
System.out.println(second_window);
driver.switchTo().window(second_window);
Thread.sleep(10000);
System.out.println(driver.getTitle());
driver.findElement(By.xpath("//*[#id='wrapp']/div[2]/div[3]/div[1]/div/div[2]/ul/li[1]/a")).click();
// ThirWindow
System.out.println("GettingID for third Window");
win = driver.getWindowHandles();
iterate = win.iterator();
first_window = iterate.next();
System.out.println(first_window);
second_window = iterate.next();
System.out.println(second_window);
String Third_window = iterate.next();
System.out.println(Third_window);
driver.switchTo().window(Third_window);
Thread.sleep(10000);
System.out.println(driver.getTitle());
Thread.sleep(3000);
driver.close();
driver.switchTo().window(second_window);
Thread.sleep(3000);
driver.close();
driver.switchTo().window(first_window);
driver.findElement(By.xpath("html/body/div[1]/div[1]/div[1]/div/div[2]/ul/li[2]/a")).click();
Thread.sleep(6000);
driver.close();
}
}
This code is not duplicate of the problem mentioned in given link below. In my issue I am getting NoSuchElementException while trying to navigate to last window.
Using Thread.sleep(3000); Your program works fine for me.I just wait 3s for getting next windows
System.out.println("GettingID for third Window");
Thread.sleep(3000);
win = driver.getWindowHandles();
iterate = win.iterator();
Please check and let me know
I have a test ready to be executed but it takes a long time to finish. In this test I'm feeding in csv data, so basically the whole test will run 56 times. I was wondering if there's anyway I could use multiple browser instance and divide the workload to four instance. It will save me some time. I tried to use TestNG's ThreadPoolSize but it's not doing what I want it to. It's using the same data for four instances of firefox. I want each browser to have it's own unique data. Please check my code and let me know what I'm missing. I really appriciate every one's help.
public class StudentPageTest {
WebDriver driver;
DesiredCapabilities capability;
WebElement element;
WebDriverWait wait;
private String baseURL;
#BeforeTest
public void setUp() throws MalformedURLException{
//capability = DesiredCapabilities.firefox();
//driver = new FirefoxDriver();
//wait = new WebDriverWait(driver, 120);
//driver.manage().deleteAllCookies();
baseURL = "http://somewebsite.com";
}
#SuppressWarnings("resource")
#Test(threadPoolSize = 4)
public void StudentPortalTest() throws InterruptedException, IOException{
driver = new FirefoxDriver();
wait = new WebDriverWait(driver, 120);
driver.manage().deleteAllCookies();
String studentId = "studentID.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
br = new BufferedReader(new FileReader(studentId));
while ((line = br.readLine()) != null) {
String[] student_id = line.split(cvsSplitBy);
//Logging in Student Portal---------------------------------------------------------------------------------------------------------------|
for (int i = 0; i < student_id.length; i++) {
driver.get(baseURL+student_id[i]);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.cssSelector(".logo>img")).isDisplayed();
driver.findElement(By.cssSelector("#UserName")).sendKeys("SecretUserName");
driver.findElement(By.cssSelector("#Password")).sendKeys("EvenMoreSecretPassword");
driver.findElement(By.cssSelector(".submitBtn")).click();
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
Thread.sleep(4000);
...............and the test goes on below...................
}
#AfterTest
public void tearDown(){
driver.quit();
}
}
You can let the Selenium grid do the task of distribution. Use TestNG to run your cases in parallel using dataprovider. Use a dataprovider to read your csv and pass one data to one #Test.
Set dataprovider thread count in your suite xml and make sure you set #DataProvider(parallel=true)
Going to your code, replace your call of instantiating a firefoxdriver to remotewebdriver to use the grid. Make sure your driver is not at class level but is a threadlocal : threadlocal<driver>.
I was trying many different ways to achieve the same thing you are trying to do. After a lot of trial and error I finally came across a solution that worked for me.
You need Selenium Grid You can then set up a few nodes to run your different browsers from
You need TestNG like you have been using but instead of trying to use threads, you will use an .xml file to pass in parameters to your test which will run the one test over and over in parallel.
If you read this document carefully and follow the steps, you should be able to achieve the same result
#Test(threadPoolSize = 4, invocationCount = 4)
Webdriver launches multiple windows after performing click action. I have tried driver.close() but it close the webdriver and test fails.
WebDriver driver = new FirefoxDriver ();
driver.get("http://www.xyz.com/");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement page = driver.findElement(By.className("coupon-rows"));
List <WebElement> coupontrigger = page.findElements(By.className("code"));
System.out.println("number of couponsTriggers on carousel = "+ "coupontrigger.size());
for (int j=0; j<=coupontrigger.size(); j++) {
js.executeScript("$('.ccode.coupon-trigger').eq("+j+").click()");
System.out.println(driver.getTitle());
driver.switchTo().defaultContent();
driver.get("http://www.xyz.com/");
page = driver.findElement(By.className("coupon-rows"));
coupontrigger = page.findElements(By.className("code"));
}
}
If I understood your requirement you want to close the other popups rather than the main window. In that case you can do below. Though I am not 100% sure of your requirement.
String mwh=driver.getWindowHandle(); // Get current window handle
Set<String> s=driver.getWindowHandles();
Iterator<String> ite=s.iterator();
String popupHandle = "";
while(ite.hasNext())
{
popupHandle = ite.next().toString();
if(!popupHandle.contains(mwh)) // If not the current window then shift focus and close them
{
driver.switchTo().window(popupHandle);
driver.close();
}
}
driver.switchTo().window(mwh); // finally move control to main window.
You can introduce a helper method which will do that task for you. You just need to find out what your current view is (WebDriver#getWindowHandle will give the one you have focus on) and then just close the rest of the windows.
private String closeAllpreviouslyOpenedWindows() {
String firstWindow = webDriver.getWindowHandle();
Set<String> windows = webDriver.getWindowHandles();
windows.remove(firstWindow);
for (String i : windows) {
webDriver.switchTo().window(i);
webDriver.close();
}
webDriver.switchTo().window(firstWindow);
return firstWindow;
}