Hi. I am trying to run the following code and test case, such that
The user is logged in
The browser is closed
The browser is started again.
Subsequently, code is executed to verify the session still exists.
public void test()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://site/login");
this.login();
driver.quit();
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://site/homepage");
this.CheckSessionExist(); /// reutrn false as the session is lost
}
My question is: shouldn't I be able to retrieve the session after I initialize another driver instance? If this is not how it works, then how can I replicate this test case?
A suggestion:
public void test()
{
IWebDriver driver = new ChromeDriver(); // This opens a window
driver.Navigate().GoToRul("https://www.google.com"); // Navigate to a dummy url, this is to keep the chrome driver session alive later
IWebElement body = driver.FindElement(By.CssSelector("body"));
body.SendKeys(Keys.CONTROL + 't'); // This opens a new window
String winHandleBefore = driver.CurrentWindowHandle();
//Switch to new window opened
foreach(String winHandle in driver.WindowHandles{
if(winHandle !- winHandleBefore)
driver.SwitchTo().Window(winHandle);
}
driver.Navigate().GoToUrl("http://site/login");
this.login();
driver.Close(); // This closes the current window, but should keep the ChromeDriver session alive
driver.SwitchTo().Window(winHandleBefore);
IWebElement body = driver.FindElement(By.CssSelector("body"));
body.SendKeys(Keys.CONTROL + 't'); // This opens a new window
String winHandleBefore = driver.CurrentWindowHandle();
//Switch to new window opened
foreach(String winHandle in driver.WindowHandles{
if(winHandle !- winHandleBefore)
driver.SwitchTo().Window(winHandle);
}
driver.Navigate().GoToUrl("http://site/homepage");
this.CheckSessionExist(); /// reutrn false as the session is lost
}
The idea here is you're
Opening a dummy window to keep the current ChromeDriver session alive
Opening a new window that you will use to navigate to your login test
Switch to that new window, navigate to the url
Login
Close that window
Switch back to the original window with the dummy url
Open another new window
Navigate to the home page
Ensure your session is still alive
Probably overly complicated, and a better solution likely exists.
Extract the cookies before closing the browser, open new browser, navigate to same domain and drop cookies
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.
There is a link behind button with PDF file on web page that I would like to access. PDF link has API key and can't be accessed directly. Button has ID company_report_link.
If I do reportDownloadButton.Click(); PDF gets opened in separate tab of browser but I can't figure out how to download it.
I have tried right click the button and select Save As? I am able to open Chrome Context menu with this one, but can't select Save link As..
// click the link to download
var reportDownloadButton = driver.FindElementById("company_report_link");
// reportDownloadButton.Click();
// if clicking does not work, get href attribute and call GoToUrl() -- this may trigger download
// var href = reportDownloadButton.GetAttribute("href");
// driver.Navigate().GoToUrl(href);
InputSimulator s = new InputSimulator();
Actions action1 = new Actions(driver);
action1.ContextClick(reportDownloadButton);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.DOWN);
Thread.Sleep(2000);
s.Keyboard.KeyPress(VirtualKeyCode.RETURN);
I have tried to do the trick with WebClient
var reportDownloadButton = driver.FindElementById("company_report_link");
var text = reportDownloadButton.GetAttribute("href");
// driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15);
WebClient client = new WebClient();
// Save the file to desktop for debugging
var desktop = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
string fileName = desktop + "\\myfile.pdf";
client.DownloadFile(text, fileName);
but it does not work because of API. Web site is giving:
System.Net.WebException: 'The remote server returned an error: (401)
Unauthorized.'
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 creating a simple news feed, it i want it can open the browser to show the details of the news, but i don't know how to close the browser , here is the code of how I open the browser,anyone can teach me how to off the browser using uwp? '
public async void test()
{
RootObject mynews = await NewsProxy.GetNews();
string website = mynews.articles[i].url;
var uriWeb = new Uri(websites);
var success = await Windows.System.Launcher.LaunchUriAsync(uriWeb);
if (success)
{
//Uri launched
}
else
{
// uri launch failed
}
}
var success = await Windows.System.Launcher.LaunchUriAsync(uriWeb);
Your code is actually telling the OS to Launch the given url and the OS in turn launches the default browser with the given URL. So you are not actually launching the browser.
In order to have full control over the browser behavior you can implement your own WebView and then use the url to navigate your WebView.
webView1.Navigate("http://www.contoso.com");
(MSDN Documentation for WebView)
How can I perform the save this page directly in pdf? I know that selenium is not able to control the chrome dialog box ... is there another way?
Page to save in pdf:
This below code will help to save page as pdf in Selenium c#.
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
protected void PDFconversion(ChromeDriver driver, string root, string rootTemp)
{
//Grid.Rows.Add(TxtBxName.Text, TxtBxAddress.Text);
try
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
Thread.Sleep(500);
js.ExecuteScript("setTimeout(function() { window.print(); }, 0);");
Thread.Sleep(500);
driver.SwitchTo().Window(driver.WindowHandles.Last());
Thread.Sleep(500);
string JSPath = "document.querySelector('body>print-preview-app').shadowRoot.querySelector('#sidebar').shadowRoot.querySelector('#destinationSettings').shadowRoot.querySelector('#destinationSelect').shadowRoot.querySelector('print-preview-settings-section:nth-child(9)>div>select>option:nth-child(3)')";
Thread.Sleep(500);
IWebElement PrintBtn = (IWebElement)js.ExecuteScript($"return {JSPath}");
Thread.Sleep(500);
PrintBtn.Click();
string JSPath1 = "document.querySelector('body>print-preview-app').shadowRoot.querySelector('#sidebar').shadowRoot.querySelector('print-preview-button-strip').shadowRoot.querySelector('cr-button.action-button')";
Thread.Sleep(1000);
IWebElement PrintBtn1 = (IWebElement)js.ExecuteScript($"return {JSPath1}");
PrintBtn1.Click();
Thread.Sleep(1000);
SendKeys.Send("{HOME}");
SendKeys.Send(rootTemp + "\\" + "result.pdf"); // Path
SendKeys.Send("{TAB}");
SendKeys.Send("{TAB}");
SendKeys.Send("{TAB}");
SendKeys.Send("{ENTER}");
Thread.Sleep(1000);
}
catch (Exception ex)
{
}
}
Another way to save is by commanding to the Chrome to save to the disk instead opening to the Page.
Below is the way to do:
ChromeOptions chromeOptions = new ChromeOptions();
// this will make automatically download to the default folder.
chromeOptions.AddUserProfilePreference("plugins.always_open_pdf_externally", true);
ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriver = new ChromeDriver(chromeDriverService, chromeOptions);
var downloadsPath = KnownFolders.Downloads.Path;
var generatedFilePngs = Directory.GetFiles(downloadsPath, string.Format("{0}*.pdf", "TheNameOfYourPDF"));
You can directly send the request to the url without Selenium involved and get the byte array with content of PDF file. After that you can read file content using some PDF library (looks like ITextSharp is popular).
Inside Chrome browser all the dialog popups are html pages so you can click on them using Selenium.
In your case you can navigate to a page, simulate Ctrl + P keyboard button press, switch to print dialog window, click Change button to change the printer, click Save to PDF, click Save button and when "Save As" box is shown - simulate Enter keyboard button press to actually save the file.
I don't do C#, but here is how that looks like in Java, in fact I have tested it and it actually works:
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_P);
robot.keyRelease(KeyEvent.VK_P);
robot.keyRelease(KeyEvent.VK_CONTROL);
// get current browser window handles and switch to window with handle that is last in the list
Set<String> windowHandles = driver.getWindowHandles();
for (String handle : windowHandles) {
driver.switchTo().window(handle);
}
driver.findElement(By.xpath("//button[contains(text(), 'Change')]")).click();
driver.findElement(By.xpath("//span[contains(text(), 'Save as PDF')]")).click();
driver.findElement(By.xpath("//button[contains(text(), 'Save')]")).click();
// you might need to add waiter here that waits a second, since script is too fast
// and needs to wait for save dialog box to be shown
robot.keyPress(KeyEvent.VK_ENTER);