How to keep Chrome open when opened using Selenium WebDriver in Mac - c#

I am trying to open Chrome and load a webpage using Selenium C# WebDriver. The issue I am having is, Chrome opens and loads the page and closes right away.
Here is my code:
//I copied the chromedriver.exe to my project directory
using (var driver = new ChromeDriver(Environment.CurrentDirectory))
{
try
{
//Maximize the browser
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("http://www.google.com");
}
catch (TimeoutException te) {
string y = te.Message;
}
catch (Exception ce) {
string k = ce.Message;
}
}
Any idea how to resolve it would be helpful.

Related

Selenium C# - While running - How should i skip the login if already logged in

Here the login code:
public void Valid_login()
{
Config config = new Config();
Login_methods login = new Login_methods();
string log_Messgae = login.Login(config.Username, config.password, config.companyID);
Assert.AreEqual("Success", log_Messgae);
if (log_Messgae == "Success")
Logged_status = "logged";
else
Logged_status = "loggedoff";
}
Here i used conditional statement but it is not working. When running the below code for each and every testcase the browser is launched and going to login page, even if i´m allready logged in.
public void Req_Search()
{
Config config = new Config();
Menus menu = new Menus();
Login_methods login = new Login_methods();
if (loginpage.Logged_status == "logged")
{
string current_Url = Driver.driver.Url;
if (!current_Url.Contains("requisition/requisition-search"))
menu.Navigate_Requisition_search();
}
else
{
login.Initilize_Driver();
loginpage.Valid_login();
menu.Navigate_Requisition_search();
}
}
When opening the the browser, selenium does not open the browser with your profile and instead opens with a default profile that has zero data about your past uses. You can use the following code to open chrome browser with your profile instead of the default profile
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumCore
{
public class Tests
{
static void Main(String[] args)
{
string currentUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
ChromeOptions options = new ChromeOptions();
options.AddArgument($"user-data-dir={currentUser}/AppData/Local/Google/Chrome/User Data");
IWebDriver webDriver = new ChromeDriver(options);
webDriver.Navigate().GoToUrl("https://www.google.com");
}
}
}
Its because selenium open your default chrome profile.
driver.AddArguments(#"--user-data-dir=C:\Users\*username*\AppData\Local\Google\Chrome\User Data");
driver.AddArguments(#"--profile-directory=*name of your profile*");
After it will load this profile cookies.
If you're running on headless, dont know why but selenium seem unable to use profiles.

Selenium C# to disable Microsoft Chromium Edge browser Sync pop-up

I am trying to test automate my application website using selenium and C# on Chromium Edge browser (version 83.0.478.45).
Every time the chromium edge driver opens up browser, it displays a pop up for sync as shown in picture below. Is there any way to stop it?
EdgeOptions used:
options.UseChromium = true;
options.AddArguments("disable-infobars");
options.AddUserProfilePreference("disable-popup-blocking", "true");
options.AddArguments("--disable-web-security");
As discussed in the comments, You can try to launch the MS Edge browser using a default profile that can help you to fix this issue.
using OpenQA.Selenium.Edge;
using System.Threading;
namespace ecwebdriver
{
public class edgewebdriver
{
static void Main(string[] args)
{
EdgeOptions edgeOptions = new EdgeOptions();
edgeOptions.UseChromium = true;
edgeOptions.addArguments("user-data-dir=C:\\Users\\username\\AppData\\Local\\Microsoft\\Edge\\User Data");
var msedgedriverDir = #"E:\webdriver";
var driver = new EdgeDriver(msedgedriverDir, edgeOptions);
driver.Navigate().GoToUrl("<website url>");
Thread.Sleep(3000);
driver.Close();
}
}
}
Sample code that modified by op.
var userDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\\Edge\\User Data");

How to handle System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

I am developing a Windows application where I manipulate Word Application. More specific, I am opening a Word Document but when I quit it and try to open another Word Document this Error comes out.
How to handle
System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) at Microsoft.Office,Word.ApplicationClass.set_Visible(Boolean Prop)**
If I don't quit the Word Application this error does not come out.
Below I show you the functions that I open and quit the Word Application.
//function to open word Document located in a specific path
public static void openWordDocument(string fileName)
{
try
{
wordApplication.Visible = true;
string filePath = myPath + fileName;
WordApi.Document docx = wordApplication.Documents.Open(filePath);
}
catch (Exception ex)
{
MyLogger.Error(ex.ToString());
}
}
//function to quit wordApplication
public static void CloseWordApp() {
try {
Object wordAppObject = Marshal.GetActiveObject("Word.Application");
WordApi.Application wordApp = (WordApi.Application)wordAppObject; //cast Object to its actual type
wordApp.Quit();
}
catch (Exception ex) {
MyLogger.Error(ex.ToString());
}
I finally figured it out what is the problem.
The main problem was that when I quit it and try to open another Word Document,which opening another Word Document means get/create an Object of Word Application. In my case wordApp != null, after finalizing the application, so I had to create another Word Application Object and return it for the case.
//open word Document located in a specific path
public static void openWordDocument(string fileName)
{
try
{
wordApplication = createWordApplicationObject(wordApplication);
wordApplication.Visible = true;
string filePath = myPath + fileName;
WordApi.Document docx = wordApplication.Documents.Open(filePath);
}
catch (Exception ex)
{
MyLogger.Error(ex.ToString());
}
}
private static WordApi.Application createWordApplicationObject(WordApi.Application wordApp)
{
WordApi.Application wordAppFirstTime;
WordApi.Application wordApp1;
if (wordApp == null)
{
wordAppFirstTime = new WordApi.Application();
return wordAppFirstTime;
}
else
{
wordApp1 = new WordApi.Application();
return wordApp1;
}
}
With CloseWordApp() remain the same.
Most probably the exception is fired by the following line of code:
wordApplication.Visible = true;
You need to make sure the COM server is alive. Because after quitting the object becomes unavailable. I'd suggest setting such object references to null, so later we could check whether the application object is still alive. For example:
try
{
if (wordApplication == null)
{
wordApplication = new Word.Application();
}
wordApplication.Visible = true;
string filePath = myPath + fileName;
WordApi.Document docx = wordApplication.Documents.Open(filePath);
}
catch (Exception ex)
{
MyLogger.Error(ex.ToString());
}
I wanted to add a solution that works for me. We had this issue in a .net web service, along with other errors, like "the remote procedure call failed" on Word.Documents.Open(). i'll list all the things we tried, and finish with the solution.
we tried:
Make sure RPC service is up. Word is not corrupted, opens properly,
including the file we were opening.
restart server and service hosting the web application.
Rollback a windows update that occured the same day it stopped working.
Uninstalled the antivirus software.
We isolated the code to a third party app to validate it was the open()
method that caused the problem, and using different files as well. We
created a win form app, and consol app. We ran that small app as win
admin, a regular account as well as the account that runs the web
app.
We ran procMon.
we did a repair on word.
we installed Office all over, we tried 32 and 64bits version
Finale solution:
we deleted the user profile that runs the web app.
4 days to find that out. I'd thought i'd share my paine with the world. lol
while posting these lines, we are not sure why the local profile created this issue.

How to download file using Firefox Headless?

I'm trying to download a XML file from specific website using selenium and Firefox Headless, but I'm not having success.
Also, If possible I need to save de downloaded file into specific folder.
Can Anyone Helps me?
Here is where I initializate my Firefox Driver:
public static FirefoxDriver callFirefox()
{
FirefoxOptions options = new FirefoxOptions();
options.AddArgument("--headless");
FirefoxDriver firefox = new FirefoxDriver(options);
return firefox;
}
And here, the other part of code:
static void Main(string[] args)
{
try
{
var ff = callFirefox();
IJavaScriptExecutor js = (IJavaScriptExecutor)ff;
ff.Navigate().GoToUrl("http://tracking.estrada.com.br/index.asp");
Thread.Sleep(1000);
ff.FindElementById("usuario").SendKeys("XXXXXXX");
ff.FindElementByName("senha").SendKeys("XXXXXXX");
js.ExecuteScript("submitform();");
Thread.Sleep(2000);
//CHANGE THE FRAME
ff.SwitchTo().Frame(0);
ff.FindElements(By.Id("f_dataini")).FirstOrDefault().SendKeys("20122018");
ff.FindElements(By.Id("f_datafin")).FirstOrDefault().SendKeys("26122018");
js.ExecuteScript("Exportar_XML();");
Console.WriteLine("CONCLUIDO");
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
}
In this website, after execute the Function js.ExecuteScript("Exportar_XML();"); the browser starts the download of XML file.

How can I remove google chrome cookies

I'm trying to remove cookies of chrome browser. Firstly I declared the path
string chromeLocation1 = "C:\\Users\\" + Environment.UserName.ToString() + "\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Local Storage";
When I try to run my remove code "The file is in use by another program or user" error appears. So I tried to kill chrome.exe's proccess
foreach (var process in Process.GetProcessesByName("chrome.exe"))
{
process.Kill();
}
But now it gives me "Access Denied" error even I run it as administrator. What should I do to remove these cookies?
You can delete all cookies with selenium framework.
1) Install selenium framework - Selenium WebDriver and Selenium WebDriver Support Classes (the easiest way to do this is by using NuGet)
2) Use the following code to delete all cookies:
var chromeUserData = "C:\\Users\\" + Environment.UserName.ToString(CultureInfo.InvariantCulture) + "\\AppData\\Local\\Google\\Chrome\\User Data";
var chromeAdvancedSettings = "chrome://settings/clearBrowserData";
var options = new ChromeOptions();
options.AddArgument("--lang=en");
options.AddArgument("--user-data-dir=" + chromeUserData);
options.LeaveBrowserRunning = false;
var driver = new ChromeDriver(options);
driver.Navigate().GoToUrl(chromeAdvancedSettings);
var frame = driver.FindElement(By.XPath("//iframe[#src='chrome://settings-frame/clearBrowserData']"));
var frameDriver = driver.SwitchTo().Frame(frame);
var dropDown = new SelectElement(frameDriver.FindElement(By.Id("clear-browser-data-time-period")));
dropDown.SelectByIndex(4);
var elm = driver.FindElement(By.Id("delete-cookies-checkbox"));
if (!elm.Selected) elm.Click();
elm = driver.FindElement(By.XPath("//button[#id='clear-browser-data-commit']"));
elm.Click();
var waiter = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
waiter.Until(wd => wd.Url.StartsWith("chrome://settings"));
driver.Navigate().GoToUrl("chrome://newtab");
[Selenium documentation]
if You want to delete your browser all data using C# language then you can delete each browser history,cookies etc (all data) using different code.
Here i write some code for deleting all data of Internet explorer
1-- Delete all data/History of Internet Explorer in a button click (Window Form application or WPF application)
private void button1_Click(object sender, EventArgs e)
{
//For internet explorer
System.Diagnostics.Process.Start("rundll32.exe", "InetCpl.cpl,ClearMyTracksByProcess 255");
}
2--- Now the importent browser Google Chrome (the mystery because everyone try to delete all history of it using SQLite but it wrong). Dont use SQLite database because google chrome Hold all data( History, Cookies, and etc) in following location
C:\Users\UserName(Your PC Name)\AppData\Local\Google\Chrome\User Data
just delete all 'User Data' Folder or all the folders and files within it. then you will see your all history and cookies clear.
Following is the code for it.
private void button1_Click(object sender, EventArgs e)
{
//For internet explorer
System.Diagnostics.Process.Start("rundll32.exe", "InetCpl.cpl,ClearMyTracksByProcess 255");
// for Google Chrome.
string rootDrive = Path.GetPathRoot(Environment.SystemDirectory); // for getting primary drive
string userName = Environment.UserName; // for getting user name
// first close all the extension of chrome (close all the chrome browser which are opened)
try
{
Process[] Path1 = Process.GetProcessesByName("chrome");
foreach (Process p in Path1)
{
try
{
p.Kill();
}
catch { }
p.WaitForExit();
p.Dispose();
}
System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(rootDrive + "Users\\"+userName+"\\AppData\\Local\\Google\\Chrome\\User Data");
try
{
foreach (FileInfo file in downloadedMessageInfo.GetFiles())
{
file.Delete();
}
}
catch { }
try
{
foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
{
dir.Delete(true);
}
}
catch { }
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
label1.Text = " History Deleted successfully.";
}
you can clear the cookies history and cache by following the below console application
https://stackoverflow.com/a/57111667/9377382

Categories