Unable to navigate to website using Java Selenium ChromeDriver with ChromeOptions - java

I am trying to use Java Selenium's ChromeDriver to log in to my own google profile and navigate to a website. However, what I found out is that if I log in to my profile, I will not be able to navigate to any website. On the other hand, if I did not log in to my profile, I can navigate to the website.
I attach the code below for your reference, the code immediately below is able to log in to profile but unable to navigate to bing website.
package Package1;
import java.util.concurrent.TimeUnit;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Options;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
public class MyClass {
public static void main(String[] args) {
// System Property for Chrome Driver
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
String userProfile = "C:\\Users\\XXXXX\\AppData\\Local\\Google\\Chrome\\User Data";
ChromeOptions options = new ChromeOptions();
options.addArguments("--user-data-dir=" + userProfile);
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.get("https://bing.com");
}
}
The code below is able to navigate to bing website, but for my usage I need it to have a profile.
package Package1;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Options;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
public class MyClass {
public static void main(String[] args) {
// System Property for Chrome Driver
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe")
WebDriver driver = new ChromeDriver();
driver.get("https://bing.com");
}
}
I know I have imported some libraries that I did not use, that should not be the problem here. How should I edit my code to make it work?

Okay solved. If I have existing chrome browser opened then the code will not be able to log in to my profile and navigate to website. But if there are no instances of chrome browser opened prior to running the code. It will work.
Will appreciate it if anyone knows why this is the way?

Related

How to get .har file or network request using selenium4

As we know One of the features added in the new version of Selenium (4.0.0-alpha-2) is a very nice Interface for Chrome DevTools API in Java.DevTools API offers great capabilities for controlling the Browser and the Web Traffic
As per documentation using the latest version of selenium we can capture the network request from the session.
Before I used browsermob for getting the network request but unfortunately they didn't update it a couple of years.
I am looking for someone who used this selenium4 dev tools API for getting all the internal request.
Can anyone suggest me how can I start to get all the requests? Thanks, advance
You can find #adiohana's example in the selenium-chrome-devtools-examples repo on gitHub.
I think youed find this test example helpful:
public class ChromeDevToolsTest {
private static ChromeDriver chromeDriver;
private static DevTools chromeDevTools;
#BeforeClass
public static void initDriverAndDevTools() {
chromeDriver = new ChromeDriver();
// dev-tools handler
chromeDevTools = chromeDriver.getDevTools();
chromeDevTools.createSession();
}
#Test
public void interceptRequestAndContinue() {
//enable Network
chromeDevTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
//add listener to intercept request and continue
chromeDevTools.addListener(Network.requestIntercepted(),
requestIntercepted -> chromeDevTools.send(
Network.continueInterceptedRequest(requestIntercepted.getInterceptionId(),
Optional.empty(),
Optional.empty(),
Optional.empty(), Optional.empty(),
Optional.empty(),
Optional.empty(), Optional.empty())));
//set request interception only for css requests
RequestPattern requestPattern = new RequestPattern("*.css", ResourceType.Stylesheet, InterceptionStage.HeadersReceived);
chromeDevTools.send(Network.setRequestInterception(ImmutableList.of(requestPattern)));
chromeDriver.get("https://apache.org");
}
You need to add the following imports:
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.Command;
import org.openqa.selenium.devtools.Console;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.network.Network;
import org.openqa.selenium.devtools.network.model.BlockedReason;
import org.openqa.selenium.devtools.network.model.InterceptionStage;
import org.openqa.selenium.devtools.network.model.RequestPattern;
import org.openqa.selenium.devtools.network.model.ResourceType;
import org.openqa.selenium.devtools.security.Security;
import java.util.Optional;

Stringing together multiple page object files in Eclipse/Cucumber/Java

I am having trouble stringing together multiple Page Object Files and step definitions.
I have imported the following, which is super heavily edited due to it being work code:
package <the package my step definition file is in>
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import <the other project my team created>.browsercapabilities.Browser;
import <the other project my team created>.Browsers;
import <a package a different step definition file is
in>.addNewContact.AddNewContactStepDefs;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import <the other project my team created>.webcomponents.WebButton;
import <my page objects package>.authenticationpages.CommandLoginPage;
import <my page object package>ThirdPageObjectFile;
import <my page object package>.SecondPageObjectFile;
import <my page object package>.FirstPageObjectFile;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
public class ThirdPageStepDefs extends BrowserBase {
private static final Logger LOG =
LoggerFactory.getLogger(ThirdPageStepDefs.class);
private WebDriver driver = mainBrowser().getDriver();
private Browser browser = Browsers.getBrowser();
private WebDriverWait wait = new WebDriverWait(driver,10);
LoginPage login = new LoginPage (browser);
SecondPageObjectFile contact = new SecondPageObjectFile (browser);
FirstPageObjectFile searchContact = new FirstPageObjectFile (browser);
ThirdPageObjectFile deal = new ThirdPageObjectFile (browser);
#Then("^I click the contacts icon$")
public void i_click_the_contacts_icon() throws Throwable {
contact.get_contact_link().clickLink();
}
I was getting an initialization error when I ran the runner code saying that the runner could not instantiate an instance of my ThirdStepDefFile, i.e. "Failed to Instantiate Class "
My runner is working fine:
package <Utility package>.utilities;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import cucumber.api.testng.AbstractTestNGCucumberTests;
#RunWith(Cucumber.class)
#CucumberOptions(
features="src\\test\\resources\\<my feature folder>",
plugin={"pretty", "html:target/cucumber-html-report",
"json:target/cucumber.json"},
glue= "<My step def folder>",
tags = "#<my tags>"
)
public class ComUITestRunner extends AbstractTestNGCucumberTests {
}
I have many more lines in scenarios that I've commented out and since I was getting the initialization error, I edited to troubleshoot as following:
-Comment all methods out (green)
-Leave all methods in (red)
-Leave one method in (red)
When I have even one method that isn't commented out, then I get an error.
My project is a series of screens that a user has to get to in order to log in. The login screen, first screen, second screen, and third screen all have their own page objects. Eventually I want to abstract those screens out to a main project that all sub projects share as they'll be pre-conditions to everything else. Stringing these screens together seems to fail and I'm considering refactoring the whole thing.
Am also new to Java/Eclipse, so it's possible that I am not seeing the stack trace correctly. For instance, the bottom of my junit screen says "62 more" lines detailing the failure that I'm not able to see. I tried debugging to no avail and I clicked on the outline on the left hand side of the junit output and when I hovered over it, it says Test Class Not Found

Glassfish & MongoDB connection error : NoClassDefFoundError

I am running a Glassfish server that is trying to connect to MongoDB. At first I created seperate projects for the server and MongoDB. So now I am trying to merge those projects but it appears anything I try to do it results in a faliure.
The current error I am getting is:
2018-07-05T19:54:36.249+0200|Severe: java.lang.NoClassDefFoundError: org/bson/conversions/Bson
I am well aware that the error happens in runtime and that the possible cause is my classpath.
Currently I copied all of my code from one project to another, added Maven dependencies and the following happens:
if I create a separate .java file for my MongoDB and run it in the same folder that the Glassfish server is, it works perfectly fine.
if I run the server and try to call methods from the other class (a little bit modified) the upper error appears
Simplified code example withouth error:
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
public class MyClass{
public static void main(String[]args){
String ip = "127.0.0.1";
int port = 27017;
MongoClient mongoClient = new MongoClient(ip,port);
/* Remaining code */
}
}
With error:
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
public class MyClass{
private MongoClient mongoClient;
public MyClass(String ip, int port){
mongoClient = new MongoClient(ip, port); // Error called here
}
/* Remaining code */
}
Called from the server.java file:
MyClass mc = new MyClass("127.0.0.1",27017);
I also tried to download all of the bson jar files separately and add them to the project but that had no effect...
The working solution for me was to delete the whole project and create it once more. Apparently there was a problem with Eclipse or I made a mistake before and forgot about it.

Selenium 3 InternetExplorerDriver Setup

I'm trying to set up a type of boiler-plate code for WebDriver that I can give to anyone in my QA team to help them test. My problem is that I can't seem to get Internet Explorer working. It's throwing errors and I have no idea how to fix them or if its some sort of naming issue.
The driver files are all in my C:\ Drive.
chromedriver.exe, geckodriver.exe, IEDriverServer.exe
Errors in the code below are //commented
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.firefox.FirefoxDriver;
import org.openqa.selenium.ie.IEDriverService; //The import org.openqa.selenium.ie.IEDriverService cannot be resolved
public class Loginmethod {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "C:\\\\geckodriver.exe");
System.setProperty("webdriver.chrome.driver", "C:\\\\chromedriver.exe");
System.setProperty("webdriver.ie.driver", "C:\\\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver(); //InternetExplorerDriver cannot be resolved to a type
driver.get("http://www.google.com/");
Thread.sleep(100);
}
}
Additionally, If anyone would know a way to test for Safari using windows 10 with selenium, that would be great.
The class you are trying to import is not the class you are using.
You are importing IEDriverService but using the InternetExplorerDriver class.
change your code to import InternetExplorerDriver.

selenium 2.0 webdriver tests compilation errors

No matter which Selenium 2.xx version web-drivers I use, I get the same compilation errors
: error reading C:\Documents and
Settings\kondojis.m2\repository\org\seleniumhq\selenium\selenium-firefox-driver\2.0b3\selenium-firefox-driver-2.0b3.jar;
error in opening zip file
This is what I have in my POM file
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium</artifactId>
<version>2.0rc2</version>
<type>pom</type> <i tried with and without type pom>
</dependency>
I am using jdk 1.6, Maven 3.0.1 M am using Maven compiler plugin 2.3.2 etc on Windows XP
package com.usps.mgo.icoa.UI;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
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.firefox.FirefoxDriver;
import org.apache.log4j.Logger;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import java.util.List;
import java.util.Locale;
/**
* Created by IntelliJ IDEA.
* User: kondojis
* Date: 2/8/11
* Time: 5:02 PM
* To change this template use File | Settings | File Templates.
*/
public class SimulatorTests {
private static final Logger logger = Logger.getLogger(SimulatorTests.class);
private static WebDriver driver;
private ReloadableResourceBundleMessageSource messageSource;
private static ClassPathXmlApplicationContext springCtx;
/**
* Properties for Simulator tests
*/
#Before
public void setUp() {
// Bootstrap Spring Framework.
springCtx = new ClassPathXmlApplicationContext(
new String[]{"test-config.xml"});
//Make Sure that test_global.properties file is always in sync with the global.properties file from production.
messageSource = springCtx.getBean("messageSource", ReloadableResourceBundleMessageSource.class);
driver = new FirefoxDriver();
}
Error in opening zip file sounds like a corrupted jar in your local repo. Try deleting the "C:\Documents and Settings\kondojis.m2\repository\org\seleniumhq\selenium\selenium-firefox-driver\" directory and making maven re-download it.
edit: Noticed your selenium dependency and error output have different versions, I declare a manual dependency like
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>2.0rc2</version>
<scope>test</scope>
</dependency>

Categories