Selenium 2: New Browser Has No Bookmarks - java

When I use Selenium 2 code (Java) to open Firefox (or any other browser) for some automated tests, the new window opens without my bookmarks, or for that matter the bookmark bar. Additionally, I suspect that cookies aren't retrieved either, because sites I normally log into do not remember certain things from my previous history.
The relevant code:
//WebDriver driver = new FirefoxDriver();
WebDriver driver = new InternetExplorerDriver();
String baseUrl = "http://localhost:8080/";
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Navigate to login page
driver.navigate().to(baseUrl + "/myApp");
//obtain the username and password elements
WebElement username = driver.findElement(By.name("username"));
WebElement password = driver.findElement(By.name("password"));
//log in
username.sendKeys("myTestLogin");
password.sendKeys("myTestPwd");
driver.findElement(By.cssSelector("input.btnStyle")).click();
...

I think by default Selenium (WebDriver) will try to use as "clean" of a profile as possible. This is so the browser's settings that a user set up don't cause testing failures. You can modify these settings if you need to. Check out http://code.google.com/p/selenium/wiki/TipsAndTricks and see if that helps get you on the right track. I haven't done this with IE before though. I think with Firefox you can even have Selenium use an existing profile if you really need it to.

Related

How can i same session id in my test when i close single open tab in Selenium?

I want run one test script. The scenario is like that;
Go to login page
Login with valid credentials
Close current single tab
Go to the login page again
Verify whether browser will go homepage instead of login page or not.
But i don't know how can i do that. Because if i use close or quit method, session id will be killed. even if i open new browser for another step, it will not be same with real scenario. Because as manually, if i try to go to login page after closing single open homepage without logging out, i can go to home page directly. I am not be able to automate it.
I used some Actions method to close and also open new tab.
And i used these;
driver.findElement(By.cssSelector(“body”)).sendKeys(Keys.CONTROL+”t”);
driver.findElement(By.cssSelector(“body”)).sendKeys(Keys.CONTROL + 'w');
I am using Selenium+Java+Cucumber+Chrome+Mac
You can use profile to achieve this scenario. I 've just given some sample code:
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--user-data-dir=C:\\Temp\\");
options.addArguments("--profile-directory=ChromeData");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("https://www.flipkart.com/");
driver.findElement(By.xpath("//input[#class='_2IX_2- VJZDxU']")).sendKeys("<username>");
driver.findElement(By.xpath("//input[#class='_2IX_2- _3mctLh VJZDxU']")).sendKeys("<password>");
Thread.sleep(1000);
driver.findElement(By.xpath("//button[#class='_2KpZ6l _2HKlqd _3AWRsL']")).click();
Thread.sleep(3000);
driver.close();
Thread.sleep(1000);
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.get("https://www.flipkart.com/");
The above code will create a new chrome profile in the directory - "C:\Temp\ChromeData", then open the browser, launch the URL, login, close the window, again open a chrome browser, launch the same URL, but this time, the user already logged in.

How to skip the login page of Salesforce?

I am currently automating test of Salesforce application and in the automation suite, logging into the application is performed numerous time. I am using Selenium + Java for the purpose of automation.
Is there any way to skip the multiple logins via; like if we can hit some login endpoint and inject the response cookies to the browser instance. Or if we can log in once and somehow save the session id or necessary cookies which could then be injected to new browser instances so that we can skip login step.
Also, I want to add on that I am using Salesforce lightning.
Any sort of help is highly appreciated :)
WebDriver has the functionality to read the cookies from the browser before closing it and then restore the cookies in the new browser window.
#Test
public void login_state_should_be_restored() {
driver = new FirefoxDriver();
driver.get("http://www.example.com/login");
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("12345");
driver.findElement(By.id("login")).click();
Assert.assertTrue(
driver.findElement(By.id("welcome")).isDisplayed());
//Before closing the browser, read the cookies
Set allCookies = driver.manage().getCookies();
driver.close();
//open a new browser window
driver = new FirefoxDriver();
//restore all cookies from the previous session
for(Cookie cookie : allCookies) {
driver.manage().addCookie(cookie);
}
driver.get("http://www.example.com/login");
Assert.assertTrue(
driver.findElement(By.id("welcome")).isDisplayed());
driver.close();
}
For more in details, please check the link
Hope this will help you.

Selenium - Log in and navigate to different page

I want to log into facebook, and then open a specific facebook url to get a list of people, working for a specific company (e.g. to get the employees of google, I need to go to https://www.facebook.com/search/str/google/pages-named/employees/present/intersect
) My first thought was to simply login (which works fine), and then go to the specific page using driver.navigate().to()
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com");
WebElement emailElement = driver.findElementById("email");
WebElement passwordElement = driver.findElementById("pass");
emailElement.sendKeys("xxxx#xxxx.com");
passwordElement.sendKeys("xxxx");
emailElement.submit();
driver.navigate().to("https://www.facebook.com/search/str/google/pages-named/employees/present/intersect");
However, this way, the facebook page is not available, and I’m prompted to log in again, even though the page is opened in the same browser tab?!
The second thought was to log in first, get the cookie, and then use is this cookie for a new driver:
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com");
WebElement emailElement = driver.findElementById("email");
WebElement passwordElement = driver.findElementById("pass");
emailElement.sendKeys("xxxx#xxxx.com");
passwordElement.sendKeys("xxxxx");
emailElement.submit();
Set<Cookie> cookies = driver.manage().getCookies();
FirefoxDriver driver2 = new FirefoxDriver();
for (Cookie cookie : cookies) {
Cookie cookieNew = new Cookie.Builder(cookie.getName(), cookie.getValue()).expiresOn(cookie.getExpiry())
.isHttpOnly(cookie.isHttpOnly()).isSecure(cookie.isSecure()).path(cookie.getPath()).build();
driver2.manage().addCookie(cookieNew);
}
driver2.get("https://www.facebook.com/search/str/google/pages-named/employees/present/intersect");
}
However, that way, an exception is thrown: org.openqa.selenium.InvalidCookieDomainException: Document is cookie-averse
What am I doing wrong?
I don't think it is a mandatory to store cookies to to get a list of people, working for a specific company. The following code block works well at my side :
driver.findElement(By.cssSelector("input[value='Log In']")).click();
driver.get("https://www.facebook.com/search/str/google/pages-named/employees/present/intersect");
System.out.println(driver.getTitle());
driver.quit();
Console Output :
Facebook Search
Apply First Thought: Setting up geckodriver for Selenium Java resolves the issue I think.
It needs to set geckodriver path with FirefoxDriver as below code:
System.setProperty("webdriver.gecko.driver", "PATH/TO/geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
Download geckodriver for your suitable OS from https://github.com/mozilla/geckodriver/releases
Extract it in a folder of your choice
Set the path correctly as mentioned above
After submit() you need to use wait functionality to refresh the page like
emailElement.submit();
//Use WebDriver wait.until() or sleep() to finish the submit action
driver.navigate().to("https://www.facebook.com/search/str/google/pages-named/employees/present/intersect");

selenium get() doesn't do anything

driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
The code below should open a firefox browser, navigate to google and search for "automation" and should navigate again to yahoo. But driver.get("http://www.yahoo.com") doesn't do anything. How will I change URL using selenium?
driver.get("http://www.google.com");
widget=driver.findElement(By.id("lst-ib"));
widget.click();
widget.sendKeys("automation");
widget.sendKeys(Keys.ENTER);
driver.get("http://www.yahoo.com");
widget=driver.findElement(By.xpath(".//*[#id='yui_3_12_0_1_1452245228407_940']/td[1]/a"));
widget.click();
The same is working fine for me after pausing/stopping the my kaspersky internet security.
driver.get("http://www.google.com");
driver.findElement(By.id("lst-ib")).sendKeys("seleniumhq");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
Thread.sleep(6000);
driver.get("http://www.yahoo.com");
Assuming you are running code on Windows, can you check your hosts file entry. You can find it in below location:
C:\Windows\System32\Drivers\etc\hosts
Have a look at the file content and check if localhost resolution has been altered.
If it does not help, post selenium version you are using, error message which you are getting.
You cannot open in same object. Two Options
Option 01:
You can open in new window like this
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
WebElement widget = driver.findElement(By.id("lst-ib"));
widget.click();
widget.sendKeys("automation");
widget.sendKeys(Keys.ENTER);
WebDriver seconddriver = new FirefoxDriver();
seconddriver.get("http://www.yahoo.com");
Option 02:
you can use keyboard keys to open new window or tab and then using driver.switchto.

Selenium Webdrivers: Load Page without any resources

I am trying to prevent Javascript from changing the site's source code I'm testing with Selenium. The problem is, I can't just simply turn Javascript off in the Webdriver, because I need it for a test. Here's what I'm doing for the Firefox Webdriver:
firefoxProfile.setPreference("permissions.default.image", 2);
firefoxProfile.setPreference("permissions.default.script", 2);
firefoxProfile.setPreference("permissions.default.stylesheet", 2);
firefoxProfile.setPreference("permissions.default.subdocument", 2);
I don't allow Firefox to load any Images, Scripts and Stylesheets.
How can I do this with the Internet Explorer Webdriver and the Chrome Webdriver? I have not found any similar preferences. Or is there even a more elegant way to stop the webdrivers from loading the site's JS Files after all?
Thank you!
Solution is to use proxy. Webdriver integrates very well with browsermob proxy: http://bmp.lightbody.net/
private WebDriver initializeDriver() throws Exception {
// Start the server and get the selenium proxy object
ProxyServer server = new ProxyServer(proxy_port); // package net.lightbody.bmp.proxy
server.start();
server.setCaptureHeaders(true);
// Blacklist google analytics
server.blacklistRequests("https?://.*\\.google-analytics\\.com/.*", 410);
// Or whitelist what you need
server.whitelistRequests("https?://*.*.yoursite.com/.*. https://*.*.someOtherYourSite.*".split(","), 200);
Proxy proxy = server.seleniumProxy(); // Proxy is package org.openqa.selenium.Proxy
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);
// start the driver ;
Webdriver driver = new FirefoxDriver(capabilities);
//WebDriver driver = new InternetExplorerDriver();
return driver;
}
Probably the easiest way to accomplish what you want in a cross-browser way is to use a proxy. This would allow you to intercept requests for resources, and block them. This would also have the advantage of using the same code for all browsers, rather than having to special-case each browser with settings unique to that browser.

Categories

Resources