I've looked extensively through Google and Stackoverflow, but i cant find a good way to implement keeping the browser open after a run and reuse it for the next run. I have it login, get text, but it closes after. I want to keep it open so I dont have relaunch the browser, login again and take more time than necessary. Simply want to use that same webpage, refresh/update the page, and get the new text(its dhtml). I have it to run every 10 seconds or so. Here what i have so far.
using (var driver = new ChromeDriver(""))
{
driver.Navigate().GoToUrl(#"");
// Get User Name field, Password field and Login Button
var userNameField = driver.FindElementByName("j_username");
var userPasswordField = driver.FindElementByName("j_password");
var loginButton = driver.FindElementByName("Submit");
// Type user name and password
userNameField.SendKeys("");
userPasswordField.SendKeys("");
// and click the login button
loginButton.Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.ClassName(""));
});
// Extract resulting message and save it into result.txt
string result = driver.FindElement(By.ClassName("")).Text;
}
Related
I try to select an option of a Button and found a working solution ;)
But i did not understand why the mostly posted standard will not work.
My solution is this line:
webdriver.FindElement(By.XPath("//select[#id='select-max-bars']/option[contains(text(), '200 000')]")).Click();
What i want to do:
Side: https://eatradingacademy.com/software/forex-historical-data/
Scroll a little down and Navigate to "Settings" (blue Text).
Here the Button for "Maximum bars" must be changed to 200.000.
Why will the Code just down not work for this?
Can anybody explain this for me?
Thank you
Here are the Side-Elements:
enter image description here
This is my not working code. The last 5 lines are the problem:
// Start driver
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = false; // hide Console
webdriver = new ChromeDriver(service);
webdriver.Manage().Window.Maximize();
webdriver.Navigate().GoToUrl("https://eatradingacademy.com/software/forex-historical-data/");
Thread.Sleep(1000);
// deny upcoming Request
webdriver.FindElement(By.Id("webpushr-deny-button")).Click();
// Navigate to Page (Link) = Settings
webdriver.SwitchTo().Frame(webdriver.FindElement(By.Id("data-app-frame")));
var statistics = webdriver.FindElement(By.XPath("//a[#class='nav-link panel-switch' and contains(text(), 'Settings')]"));
Actions actions = new Actions(webdriver);
actions.MoveToElement(statistics);
actions.Perform();
statistics.Click();
// Click Button "Reset"
webdriver.FindElement(By.Id("btn-reset-settings")).Click();
// for Test only: Button can be clicked
// //webdriver.FindElement(By.Id("select-max-bars")).Click();
// How to select the Option in the "Drop Down" Button "Maximum Bars" ?
// This here will not work for me:
// ###################################################################
SelectElement objSelect = new SelectElement(webdriver.FindElement(By.Id("select-max-bars")));
Thread.Sleep(15);
//objSelect.selectByText("200 000");
objSelect.SelectByValue("200000");
I am making a bot that list all the given assembled letters to make the players connect or build a word around that given value of assembled letters, im very new to selenium and still grasping the best practices thanks in advance. (https://jklm.fun "BombParty")
https://i.stack.imgur.com/wGyMd.png
What we want to achieve:
//locate the element (the one the center of that bomb)
//extract the elements displayed value (the label)
//Console Log that value
My Code:
ChromeOptions options = new ChromeOptions(); //creating chrome driver options to add some commands to remove the message "This is automated . . ."
options.AddAdditionalCapability("useAutomationExtension", true);
options.AddExcludedArgument("enable-automation");
options.AddArgument("window-size=1200x600");
var driver = new ChromeDriver(options); //declear our driver for us to automate and control
driver.Navigate().GoToUrl("https://jklm.fun/QVVC"); // go to our targeted uri
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(25); // wait for sometime to give our client to load
// let our user enter the username or join a game
while (true) // loop our funtion to locate and extract the given word
{
try
{
driver.FindElements(By.CssSelector("div.syllable")); //we did a FindElements because the label can change value over time and state another syllable
Console.WriteLine("Success!");
}
catch
{
Console.WriteLine("Failed!");
}
}
The Output of my Code:
Success!
What I Have tried:
var word = driver.FindElement(By.CssSelector("div.syllable"));
Console.WriteLine(word.Text.ToString());
The Result: Failed!
Update:
So i tried to get the value after it finds it and i will find it again,it was a success but it only returns this string, how to fix this?
The update
I'm trying to automate TextNow using Selenium but when I add Username and password, I am getting an error "Username or Password is invalid". But, the same is working fine manually.
below is the code which i tried
static void Main(string[] args)
{
IWebDriver driver;
driver = new ChromeDriver("cromepath");
driver.Url = "https://www.textnow.com/messaging";
driver.Manage().Window.Maximize();
IWebElement userName = driver.FindElement(By.Id("txt-username"));//txt-password
IWebElement password = driver.FindElement(By.Id("txt-password"));
userName.SendKeys("username");
password.SendKeys("password");
IWebElement login = driver.FindElement(By.Id("btn-login"));
login.Click();
}
You mentioned you get an error that username / password are invalid. Are you sure you are sending the right credentials?
Your XPath is correct here, so waiting for element to exist is most likely issue
-- textnow.com does take a minute to load. You might also want to clear both WebElements before sending keys.
using OpenQA.Selenium.Support.UI;
// declare wait of 15 seconds
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
// wait for element to exist, then store it in username variable
var username = wait.Until(drv => drv.FindElement(By.Id("txt-username")));
// clear & send keys
username.Clear();
username.SendKeys("username");
The same approach can be repeated for password.
If you are still getting username / password invalid, and you are sure you are using correct credentials, then it's possible SendKeys() is happening too quickly & keystrokes are not all registering in the input fields..
You can wrap SendKeys() in a method to slowly send keys, in case the input entering too quickly is a problem:
public static void SlowlySendKeys(this IWebElement element, string text)
{
// first clear element
element.Clear();
// slowly send keys, wait 100ms between each key stroke
foreach (var c in text) {
element.SendKeys(c);
System.Threading.Thread.Sleep(100);
}
}
Then, you can call:
username.SlowlySendKeys("username");
This will slow down key strokes and work around issue where key strokes are sent too quickly.
I'm running a Selenium test in C# to open a URL, log in using a supplied username & password, then navigate to a page containing downloadable reports. See my code below (note: website names and usernames/passwords are withheld):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Support.UI;
namespace SeleniumProject
{
class SeleniumTest
{
public static void Main(string[] args)
{
#region Constants
//User Account Information
const string username = "MyUsername";
const string password = "MyPassword";
//Initial Login Page URL and Elements
const string urlLogin = "MyURL";
const string usernameLoginName = "username";
const string passwordLoginName = "password";
const string submitLoginClassName = "btnAlign";
//Welcome Page Element
const string profileWelcomeClassName = "mstrLargeIconViewItemLink";
#endregion
int elementListIndex = 0;
IWebDriver driver = new InternetExplorerDriver();
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl(urlLogin);
driver.FindElement(By.Name(usernameLoginName)).SendKeys(username);
driver.FindElement(By.Name(passwordLoginName)).SendKeys(password);
driver.FindElement(By.ClassName(submitLoginClassName)).Click();
if (driver.Title == "Servicer Performance Profile Home. MicroStrategy")
{
try
{
driver.FindElement(By.ClassName(profileWelcomeClassName)).Click();
}
catch (NoSuchElementException ex)
{
//failed
}
}
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.XPath("//img[contains(#src,'images/freddiemac/sppdash/navigation-drawer-1.png')]")));
IReadOnlyList<IWebElement> elementList = driver.FindElements(By.XPath("//img[contains(#src,'images/freddiemac/sppdash/navigation-drawer-1.png')]"));
string mainHandle = driver.CurrentWindowHandle;
foreach (var element in elementList)
{
if (element.Displayed && elementListIndex == 5)
{
element.Click();
driver.FindElement(By.XPath("//div[contains(.,'EDR Overview')]")).Click();
break;
}
else
{
elementListIndex++;
}
}
}
}
}
What's happening is whenever I execute that last Click() event that's within the if statement nested inside of the foreach loop, instead of the normal behavior of the link opening a new tab in the same IE, it's opening as a new window and reverting back to a prior page. Normally, whenever I log into this website manually and click this link, a new tab is opened that contains another download link inside of it; that's the page I'm trying to get to.
I have no idea why this new browser window is opening with a prior page instead of even the target page I'm requesting. Could this have something to do with Selenium & IE11 not getting along? Another idea is the current login session expiring somehow, but this is all being executed in less than 10 seconds, so I wouldn't assume this is the issue.
Does anyone have any ideas?
This issue has been resolved. After many, many failed attempts at changing IE settings for handling new tabs, executing JavaScript onclick() events programmatically (instead of using native browser click commands), opening and switching between empty tabs, trying right-click keyboard commands, etc., the issue came down to IE simply not being compatible with what I was trying to do. First attempt with Google Chrome proved to be successful. The website behaved normally and links that were supposed to trigger a new tab indeed triggered the new tab.
My advice to those of you new to Selenium webdriver testing, whether your language is C# or something else, is to avoid Internet Explorer at all costs. Even with IE 11, none of what I was wanting to do worked. Test using Chrome as your first choice. Maybe it will save you three working days of troubleshooting and debugging.
I have written several Selenium Website Tests, however, this is my first with a site that is set to Windows Authentication.
I have been trying with Chrome and IE.
With IE I can successfully login to the site, and I see AutoIt typing and I can see that the browser successfully loads the correct page after login, however, the driver never has a connection to that browser.
With Chrome, I can never find the window to connect with AutoIt.
Using C#. See inline code comments for more specifics on the errors.
try
{
var autoIT = new AutoItX3();
if (IE) //IE Driver - Driver looses connection with the window immediately on Navigate, but AutoIT login works.
//(Driver does work fine if I go to a non-windows authentication site)
{
driver.Navigate().GoToUrl(testConfig.Url);
System.Threading.Thread.Sleep(2000);
//driver.CurrentWindowHandle crashes, 'No Window Exits'
var driverHandles = driver.WindowHandles; //result is 0
var test4 = autoIT.WinActive("Windows Security");
autoIT.WinActivate("Windows Security");
autoIT.Send("zzzzzzz");//Don't need user as it remembers
System.Threading.Thread.Sleep(1000);
autoIT.Send("{TAB}");
autoIT.Send("{ENTER}");
//Visually I can see Browser is logged in and full page loads.
autoIT.WinActivate("EDB Data Manager - Internet Explorer");
var test5 = autoIT.WinGetTitle("EDB Data Manager - Internet Explorer");
System.Threading.Thread.Sleep(2000);
driver.Url = testConfig.Url;
System.Threading.Thread.Sleep(2000);
var driverHandles2 = driver.WindowHandles; //result is still 0
//this will fail
IWebElement userName = driver.FindElement(By.Id("WellsCard"));
//I've tried refreshing or navigating to the url again with no success.
}
else //chrome Driver Driver maintains connection with the window immediately, but AutoIT fails, as I can't find window.
{
driver.Navigate().GoToUrl(testConfig.Url);
System.Threading.Thread.Sleep(2000);
var test7 = autoIT.WinExists("Authentication Required");
var tes8 = autoIT.WinExists("data:, - Google Chrome");
var test9 = autoIT.WinExists("EDB Data Manager - Internet Explorer");
var test10 = autoIT.WinExists("Untitled - Google Chrome");
//None exist, so this will not work.
autoIT.WinActivate("Authentication Required");
autoIT.Send("myUserName");
autoIT.Send("{TAB}");
autoIT.Send("zzzzz");
System.Threading.Thread.Sleep(1000);
autoIT.Send("{TAB}");
autoIT.Send("{ENTER}");
}
}
catch (Exception ex)
{
output.OutputMessage(ex.ToString());
}