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.
Related
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.
I am running my test case on 2 different browser "Chrome" and "Firefox".I am trying specified the path of my file to be downloaded during the [test] is running for "Chrome". All the code work as expected, I am able to save my file in the specified path. My "Firefox" is working fine but not for "Chrome". It just that every time when I run my script,it will open 2 "Chrome" browser , ( (1st) just open and do nothing ) , (2nd)(run the script as expected)). So on every test case i run , it will run all the test case on the 2nd "Chrome" browser.Furthermore, I couldnt use the [TearDown] method to close the browser, because it run on the 2nd "Chrome" browser , instead of the 1st "Chrome
[TestFixture(typeof(ChromeDriver))]
[TestFixture(typeof(FirefoxDriver))]
public class Program<TWebDriver> where TWebDriver : IWebDriver, new()
{
IWebDriver driver;
IWebElement element;
[SetUp]
public void StartBrowser1()
{
driver = new TWebDriver();
ICapabilities caps = ((RemoteWebDriver)driver).Capabilities;
string browserName = string.Empty;
if (caps.HasCapability("browserName"))
{
browserName = caps.GetCapability("browserName").ToString();
if (browserName.Equals("chrome"))
{
String myDownloadFolder = #"c:\temp\GoogleChrome\";
var options = new ChromeOptions();
options.AddUserProfilePreference("download.default_directory", myDownloadFolder);
driver.Manage().Window.Maximize();
driver = new ChromeDriver(options);
}
}
// For firefox
else if (browserName.Equals("firefox"))
{
String myDownloadFolder = #"c:\temp\MozillaFirefox\";
FirefoxProfile fp = new FirefoxProfile();
fp.SetPreference("browser.download.folderList", 2);
fp.SetPreference("browser.download.dir", myDownloadFolder);
fp.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
// disable Firefox's built-in PDF viewer
fp.SetPreference("pdfjs.disabled", true);}
Base.Login(driver); // base class , the code for the base class
/* public static void Login(IWebDriver driver)
{
driver.Manage().Window.Maximize();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
driver.Navigate().GoToUrl("http://192.163.0.1/admin/Login/Login.aspx");
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).SendKeys("abc");
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtPassword")).SendKeys("123456");
driver.FindElement(By.Id("ctl00_MainContent_ucLogin_cmdLogin")).Click();
}
*/
}
[TearDown]
public void CloseBrowser()
{
Base.Logout(driver);
}
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.
This is the initial start page for the WebDriver server observed on IE with different localhost and port number shown on my screen.
I have put my code sample below. Please help me out.
IE version: 11 (32 bit)
Selenium IE Webdriver : 3.141.5.0 (32 bit)
C# language
I tried solutions given in stack overflow by Enabling all protected zones.
public static void Main(string[] args)
{
IWebDriver driver = new InternetExplorerDriver();
string url = #"http://www.google.com";
driver.Navigate().GoToUrl(url);
Thread.Sleep(10000);
Console.WriteLine("Ending");
driver.Quit();
}
It is expected to open google.com. But shows me This is the initial start page for the WebDriver server.
Please make sure you have downloaded the "IEDriverServer.exe" first, then, you could use the following code to use the webdriver:
private const string URL = #"http://www.google.com";
// DriverServer path. You could download the server from http://selenium-release.storage.googleapis.com/index.html. then get the path.
private const string IE_DRIVER_PATH = #"D:\Downloads\webdriver\IEDriverServer_x64_3.14.0";
static void Main(string[] args)
{
var options = new InternetExplorerOptions()
{
InitialBrowserUrl = URL,
IntroduceInstabilityByIgnoringProtectedModeSettings = true
};
var driver = new InternetExplorerDriver(IE_DRIVER_PATH, options);
driver.Navigate();
driver.Close(); // closes browser
driver.Quit(); // closes IEDriverServer process
Console.ReadKey();
}
The selenium webdriver was not compatible with the browser. It needed re-installation of the webdriver to match browser. It works fine now.
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