How to open a mobile version website using Selenium WebDriver? - java

I have the following code to open the mobile version of Facebook in Firefox in my Desktop by changing the user-agent.
#Test
public void fb() {
FirefoxProfile ffprofile = new FirefoxProfile();
ffprofile.setPreference("general.useragent.override", "iPhone"); //this will change the user agent which will open mobile browser
WebDriver driver = new FirefoxDriver(ffprofile);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().setSize(new Dimension(400,800)); //just to change the window size so that it will look like mobile ;)
driver.navigate().to("http://www.facebook.com/");
driver.findElement(By.name("email")).sendKeys("username");
driver.findElement(By.name("pass")).sendKeys("************");
driver.findElement(By.name("login")).click();
}
But for some reason, it doesn't seem to work quite right. Can anyone let me know what I'm doing wrong here?

try sending a request to http://m.facebook.com, this is facebooks mobile website, This will only work if its just for facebook though.

Related

Disable popup "Restore Pages? Chrome didn't shut down correctly." in selenium webdriver Java

Though I have seen some related questions, I am putting this question again as I am still facing the issue.
I have a website that asks for login verification code on first time login and then it does not ask in further login instances. If I dont use a custom browser profile, the site asks verification code every time when selenium runs the login. Hence I have used customed browser profile as below (this is not the question)
options.addArguments("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\default");
Then, After the test is finished, I quit the browser using
driver.quit();
Problem is, next time I run the test again, the chrome browser opens with the popup "Restore Pages? Chrome didn't shut down correctly." and the site asks for verification code again after login. Entering verification code is not part my script, so the script fails. Then I close the browser manually by clicking on the X on the top corner.
Then I run the test again, chrome browser opens Normally without the popup and the site does not ask for verification code, login is successful. then, script closes browser itself by the driver.quit().
Then I run the test again, chrome browser opens with the popup and test fails again.
This shows that driver.quit() is not closing the browser correctly.
I have tried several settings, but still the popup is coming.
preferences file -> "exit_type":"none" (as well as "normal") and exit cleanly = true
site settings -> pop-ups and redirects -> Blocked (recommended)
I have also tried checking alerts exists or not, but it says "No alert". Script does not detect the popup as alert.
How can I make sure the browser is opened NORMALLY every next time after driver.quit() closes the browser in the previous test run? Please help.
Below is my code: I use chrome extension, so I cannot disable extension also.
String extFilePath = "C:\\ChromeDriver\\Salesforce_inspector.crx";
System.setProperty("webdriver.chrome.driver","C:\\chromedriver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(extFilePath));
options.addArguments("--disable-notifications");
options.addArguments("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\default");
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
try
{
driver.switchTo().alert();
System.out.println("alert accepted");
} // try
catch (NoAlertPresentException Ex)
{
System.out.println("No alert");
}
driver.get("salesforce url");
I dont want to use incognito mode, because I need to retain the cookies and passwords to prevent the login verification code issue mentioned earlier.
I solved this issue setting the exit_type to normal in the preferences after set up the user dir.
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.exit_type", "Normal");
options.setExperimentalOption("prefs", prefs);
In your case will be something like this
String extFilePath = "C:\\ChromeDriver\\Salesforce_inspector.crx";
System.setProperty("webdriver.chrome.driver","C:\\chromedriver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(extFilePath));
options.addArguments("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\default");
options.addArguments("--start-maximized");
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.exit_type", "Normal");
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
try
{
driver.switchTo().alert();
System.out.println("alert accepted");
} // try
catch (NoAlertPresentException Ex)
{
System.out.println("No alert");
}
driver.get("salesforce url");

Is it possible to reuse selenium session in chrome headless?

I have an upload sequence code that I am running using remote debugging to save me verification each time. I was wondering if it was possible for a session to be both headless and in remote debugging seeing as I cant use computer while it runs for some reason. if chrome is minimized it fails to find certain elements.
I have
// connect to remote debugging
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("debuggerAddress", "localhost:9222");
also the piece of code that fails when chrome is minimized is:
// click on zip
try {
WebElement element_1=driver_2.findElement(By.xpath("//*[text() = 'zip.zip']"));
WebDriverWait wait = new WebDriverWait(driver_2, 120);
wait.until(ExpectedConditions.elementToBeClickable(element_1));
element_1.click();
}catch (org.openqa.selenium.NoSuchElementException e) {System.out.println("no such element");}

Clear InternetExplorerDriver cookies selenium webdriver

When I create my internetExplorer instance, I use the following:
public static WebDriver internetExplorerWebWDriver() {
DesiredCapabilities returnCapabilities = DesiredCapabilities.internetExplorer();
returnCapabilities.setCapability(InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING, false);
returnCapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
returnCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
returnCapabilities.setCapability("ignoreZoomSetting", true);
return new InternetExplorerDriver(returnCapabilities);
My problem is: I have to open a secondary internetExplorer window with cleared cookie/Cache/Session and authenticate a user during the login.
Right now, using this code, cookie is not deleted because authentication not appears and I cannot login with different user. (seems to me, the first login is saved, and used in the second window)
Any ideas? Thanks!
Have you tried restarting IE after calling DeleteAllCookies each time ?
Placing a driver.quit() in the after class if you using junit ?
I have experimented similar problems, try with the code below in #Before method:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("localStorage.clear();");
js.executeScript("sessionStorage.clear();");
driver.manage().deleteAllCookies();

Using Selenium on https web application that runs over vpn

First of all, I need to state that I am total beginner with Selenium.
I am trying to test an application in firefox browser using Selenium. Due to security issues the application works only over vpn.
My problem occurs with the following steps; I create the webdriver and navigate to the start (login) page of application. I get an "Authorization request" popup. If I cancel the popup, then I get to a page that states "Connection is not secure" (it's https address). After I get passed that, I lose the part where Selenium program should populate username and password and it just stays on the login page.
My question, is there a way to start Selenium testing on an application so that it is already opened and prepared (ie logged in) in browser? I am not happy that username and password are hard-coded in Selenium code.
If that is not possible, how do I skip that authorization popup and problem with non-secure connection? How do I populate username and password in safest way?
Thanks!
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Selenium-java-3.0.1\\geckodriver.exe");
// I tried also with this code bellow in comment, but it did not work, it did not even get to login page
//WebDriverWait wait = new WebDriverWait(driver, 10);
//Alert alert = wait.until(ExpectedConditions.alertIsPresent());
//alert.authenticateUsing(new UserAndPassword("cfadmin", "20lipim18"));
driver.get("https://Application_login_page.com");
driver.findElement(By.xpath(".//*[#id='login']")).click();
driver.findElement(By.xpath("[#id='login']")).sendKeys("Username");
}
if it's possible, is there a way to start Selenium testing on application that is already opened and prepared (logged) in browser?
Try using firefox profile. Since selenium open fresh instance of browser by default. You can use your own firefox frofile.
This is a code to implement a profile, which can be embedded in the selenium code.
ProfilesIni profile = new ProfilesIni();
// this will create an object for the Firefox profile
FirefoxProfile myprofile = profile.getProfile("default");
// this will Initialize the Firefox driver
WebDriver driver = new FirefoxDriver(myprofile)
It will also maintain the session means you are already login to the application in firefox(default profile). Then if you execute the script, you will see that you are already logged in to the application.
There is no way to open already authorised page, you have to have to pass username and password through selenium script.
You may use below code to do the authentication
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));

how to avoid google search detect selenium webdriver as unusual behaviour?

I try to use selenium webdriver to do one search by image in google so my user didn't need to manually open the browser and paste image url there. but google say
Our systems have detected unusual traffic from your computer network. This page checks to see if it's really you sending the requests, and not a robot.
And give captcha, is there a way to avoid being detected as automation by google using selenium webdriver?
here my code:
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://images.google.com/searchbyimage?image_url=";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test2() throws Exception {
driver.get(baseUrl + "http://somesite.com/somepicture.jpg");
driver.findElement(By.linkText("sometext"));
System.out.println("finish");
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
It appear that google detect browser profile to determine something strange has going on or not. for example if you do private browsing with your browser(i test it with firefox and chrome), your browser profile will change to anonymous, so google will find it suspicious and request you to fill captcha.
That case also happen when you run your browser from selenium webdriver.
So you need to set the selenium driver profile to your default profile by using some code like this(currently only work on firefox)
ProfilesIni allProfiles = new ProfilesIni();
WebDriver driver = new FirefoxDriver(allProfiles.getProfile("default"));
I disagree with #Angga and doubt that Google knows that you're a bot because you're NOT in your default profile.
It's more likely because of this:
Can a website detect when you are using selenium with chromedriver?
Just add a single line, it will surely help
#For ChromeDriver version 79.0.3945.16 or over
options.add_argument('--disable-blink-features=AutomationControlled')
#Open Browser
browser = webdriver.Chrome(executable_path='chromedriver.exe',options=option)

Categories