I Need to get the current URL. Split that URL and store it in a string.
What I have tried is -
String urlSecondpart = this.getDriver().getCurrentUrl().Split("/a/")[1];
This opens a new url not the current URL
You are doing something wrong in your code but you haven't posted enough for us to see the problem. Do some reading and create a 2 line script and make sure the basics are working.
IWebDriver driver = new FirefoxDriver();
String currentURL = driver.Url;
If they aren't, you have something installed incorrectly or version mismatching. Fix that and try again. If it is working, you will have to debug your script by placing a breakpoint when the script starts and walking through your code until you find the problem.
Read How to create a Minimal, Complete, and Verifiable example, especially the last link on how to debug small programs.
Here I'm using Firefox profile as an example
FirefoxProfile firefoxProfile = new FirefoxProfile();
// todo: initialize your profile using firefoxProfile.SetPreference
IWebDriver driver = new FirefoxDriver(firefoxProfile);
string url = driver.Url; // get the current full URL
Then make use of standard string operation to extract what you want.
For the details in SetPreference and setting up a profile, please refer to http://www.seleniumhq.org/docs/
Create a static object of the driver once outside of the main method and within a class.
public class Test
{
public static IWebDriver driver = new FirefoxDriver();
static void Main(string[] args) {
// Here your code
string url = driver.Url;
}
}
It will give you an URL of the current page.
Related
I started using selenium with CS and have one issue. When code is compiled, program cannot find webdriver path, because it's being moved into the .exe file. I fixed this problem, by copying driver into the bin folder, so program can access it again. However, I want it to be able to access that driver inside .exe file.
I was doing this in python using os path:
def resource_path(relative_path: str) -> str:
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.dirname(__file__)
return os.path.join(base_path, relative_path)
If anyone knows how to do this in cs, please let me know.
Code that I'm using in c#:
var browser = new EdgeDriver();
browser.Navigate().GoToUrl(link);
webdrivermanager should be more helpful here. you can add its Nuget and use to manage drivers for browsers without requiring the driver exe files.
I use something like this and call this method everytime I need a browser.
public static InternetExplorerDriver InitBrowser(string browserName)
{
switch (browserName)
{
case "IE":
{
var IE_DRIVER_PATH = #"C:\PathTo\IEDriverServer";
InternetExplorerDriver driver = new InternetExplorerDriver(IE_DRIVER_PATH);
return driver;
}
}
return null;
}
This allows you to define the path from which to grab the driver, and so you wont have to depend on it being in your BIN folder. There are other solutions but this is what I have that works really well for me. You are set up to use this method for other browsers by adding more switch cases, and also from here you can easily add your browser options. You can call the method in your tests using:
InternetExplorerDriver driver = InitBrowser(IE);
Here it is simplified without the switch case:
var IE_DRIVER_PATH = #"C:\PathTo\IEDriverServer";
InternetExplorerDriver driver = new InternetExplorerDriver(IE_DRIVER_PATH);
I am new to coding. I am trying to make a simple console app that will run internet speed test. I've searched all over and I couldn't find the answer. I tried all the sample answers but I couldn't get the program to run. For now, my program returns 0 which is a value from HTML source document. I need the value from javascript. the website is https://fast.com/en/ I only need the speed test results. I need help. here is my code:
enter code here
class Program
{
[STAThread]
static void Main(string[] args)
{
HtmlWeb web = new HtmlWeb();
string url = "https://fast.com/en/";
HtmlDocument doc = web.LoadFromBrowser(url, html =>
{
return !html.Contains
("<div class=\"speed-results-container succeeded\"
id=\"speed_value\" ></div>");
});
var t1 = doc.DocumentNode.SelectSingleNode
("//div[#id='speed-value']").InnerText;
Console.WriteLine($"{t1}");
}
}
So the whole "magic" of the test is made in app-ea56f7.js file.
This file is sending request and receiving chunks of data from netflix. Unfortunately, as referenced in Running Scripts in HtmlAgilityPack there is no direct way of having this without using a headless browser.
Either use https://www.npmjs.com/package/speedtest-net
currently I have the following code using selenium and phantomjs in c#:
public class Driver
{
static void Main()
{
using (var driver = new PhantomJSDriver())
{
driver.Navigate().GoToUrl("https://www.website.com/");
driver.Navigate().GoToUrl("https://www.website.com/productpage/");
driver.ExecuteScript("document.getElementById('pdp_selectedSize').value = '10.0'"); //FindElementById("pdp_selectedSize").SendKeys("10.0");
driver.ExecuteScript("document.getElementById('product_form').submit()");
driver.Navigate().GoToUrl("http://www.website/cart/");
Screenshot sh = driver.GetScreenshot();
sh.SaveAsFile(#"C:\temp\test.jpg", ImageFormat.Png);
}
}
}
My objective is to be able to add a product to my cart and then checkout automatically. The screenshot is just included to test whether the code was successfully working. My first issue is that I often get an error that it cannot find the element with product id "pdp_selectedSize". I'm assuming this is because the the webdriver hasn't loaded the page yet, so I'm looking for a way to keep checking until it finds it without having to set a specific timeout.
I'm also looking for faster alternatives to use instead of a headless browser. I used a headless browser instead of http requests because I need certain cookies to be able to checkout on the page, and these cookies are set through javascript within the page. If anyone has a reccommendation for a faster method, it would be greatly appreciated, thanks!
For your first question, it would behoove you to look into using ExpectedConditions' which is part of theWebDriverWaitclass inSelenium`. The following code sample was taken from here and only serves as a reference point.
using (IWebDriver driver = new FirefoxDriver())
{
driver.Url = "http://somedomain/url_that_delays_loading";
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>(d =>
d.FindElement(By.Id("someDynamicElement")));
}
More on WebDriverWaits here.
As to your second question, that is a really subjective thing, in my opinion. Headless Browsers aren't necessarily any faster or slower than a real browser. See this article.
I am writing a script in Selenium WebDriver using C#. In the script, I am downloading some documents from the webpage and I want to download it in a dynamic path. I am using ChromeOptions class and its method to accomplish the task. Here is my sample code:
ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("download.default_directory", "C:\Users\Desktop\MyDownloads");
IWebDriver driver = new ChromeDriver(#"C:\Users\chromedriver_win32\" , options);
If I am using the above code in the starting of the function then it works fine.
However, I want to set the properties of ChromeOptions class in the middle of the function because my path is dynamic. Hence I just change the hard coded path with the string variable and put the following code in the middle of the function
ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("download.default_directory", strDownloadFinalPath);
IWebDriver driver = new ChromeDriver(#"C:\Users\chromedriver_win32\" , options);
Now, when I am updating the ChromeOptions in the middle of the function or at run time, then Its creating another instance of a ChromeDriver and its opening one more chrome window. It does not update the properties of ChromeOptions class. I did some experiments like removing the path of chromedriver.exe from IChromeDriver class but it started giving the following error:
The chromedriver.exe file does not exist in the current directory or
in a directory on the PATH environment variable.
What could be the way to set the ChromeOptions in the middle of the code without creating an another instance of a IWebDriver Class?
You can only set ChromeOptions, and thus the download path, via the class constructor(s). There is no property you can update once you've instantiated ChromeDriver. So the answer to your final question ("without creating another instance") is, you cannot.
What I have done to deal with this is to check the "Ask where to save each file before downloading" setting in Chrome and then I interact with the Save As dialog prompt in my test inputing the full dynamic save file path and clicking save. The problem is that this is a Windows dialog and Selenium cannot interact with it. I am using MS CodedUI to work with it. My dialog class for the Save As prompt:
using Microsoft.VisualStudio.TestTools.UITesting.WinControls;
public class WindowsDialogBoxView : WinWindow
{
public WindowsDialogBoxView()
{
this.SearchProperties[WinWindow.PropertyNames.ClassName] = "#32770";
}
public WinEdit FilenameEdit
{
get
{
this.filenameEdit = new WinEdit(this);
this.filenameEdit.SearchProperties[WinEdit.PropertyNames.Name] = "File name:";
return this.filenameEdit;
}
}
private WinEdit filenameEdit;
Usage:
WindowsDialogBoxView WindowsDialogBox = new WindowsDialogBoxView();
Keyboard.SendKeys(WindowsDialogBox.FilenameEdit, "C:\\myFileSavePath\\Blah\\FileToSave.abc");
I had difficulty interacting with the Save button of the dialog so I use Keyboard.SendKeys("{ENTER}"); You may have to add some {TAB}s in there.
I want to automate mobile web site testing on Android emulator using c# and Appium. There is a simple test scenario I want to automate for the start:
1. Start Browser
2. Find an element
3. Clear it
4. Send keys
I've got a problem with the second step. Every time MSTest tries to execute FindElementById line in the code below, I get the error:
"An element could not be located on the page using the given search parameters."
[TestClass]
public class UnitTest1
{
private DesiredCapabilities _capabilities;
private AndroidDriver _driver;
public void InitializeDriver()
{
Console.WriteLine("Connecting to Appium server");
_capabilities = new DesiredCapabilities();
_capabilities.SetCapability("deviceName", "test_02");
_capabilities.SetCapability(CapabilityType.BrowserName, "Chrome");
_capabilities.SetCapability(CapabilityType.Version, "5.0.1");
_capabilities.SetCapability(CapabilityType.Platform, "Android");
//Application path and configurations
_driver = new AndroidDriver(new Uri("http://127.0.0.1:4723/wd/hub"), _capabilities);
}
[TestMethod]
public void TestMethod1()
{
InitializeDriver();
var element = _driver.FindElementById("com.android.browser:id/url");
element.Clear();
element.SendKeys(#"http://stackoverflow.com/");
}
}
Input string for the method I've got from UIAutomator that is shown below.
I tried several combinations for the FindElementById input method:
"com.android.browser:id/url"
"id/url"
"url"
but no luck.
My environment:
Windows 8.1
Appium 1.3.4.1
ChromeDriver 2.14.313457
Android Device Monitor 24.0.2
Sorry for misleading !!!
In case of testing web apps in browser the elements should be located as usual elements on the web page ( not as some classes like android.widget.EditText and android.widget.Button). So try for example the following and you will see some result:
var element = _driver
.findElementByXPath("//input[#id='lst-ib']");
To get locators you should run the browser on your desktop, open the page and use some tools/extensions like Firebug in Firefox or Firebug Lite in Chrome browser.
Try these 2 statements:
var element = _driver.FindElement(By.Id("com.android.browser:id/url");
driver.findElementsByXPath("//*[#class='com.android.browser' and #index='1']");
Update ! The following approach is not for web testing:
Could you try to find the element using xpath?
#FindBy(xpath="//android.widget.EditText[contains(#resource-id, 'url')]")
So in your case you can try the following:
var element = _driver.findElementByXPath("//android.widget.EditText[contains(#resource-id, 'url')]");
Update: in case of testing web apps (not native) you should use web page locators instead of Android classes.