C# Selenium bot element selection trouble - c#

I am trying to make a bot that goes through drop-downs and makes selections but it's having trouble finding the element. The code is below.
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.Extensions;
using OpenQA.Selenium.Support.UI;
namespace selenium_test
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver;
driver = new ChromeDriver("C:\\");
Console.WriteLine("ChromeDriver Initialized");
driver.Url = "https://odyssey.gwinnettcourts.com/Portal/Home/Dashboard/26";
IWebElement typeElement = driver.FindElement(By.XPath(".//option[#id='cboHSSearchBy']"));
var typeSelect = new SelectElement(typeElement);
typeSelect.SelectByValue("JudicialOfficer");
typeElement.Click();
}
}
}

what exactly is the error? I can only assume that it is taking time to find element.
add wait time maybe? also, why using xpath when you have id of controls? id is quicker!
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists((By.Id("cboHSSearchBy"))));

Related

target frame detached Selenium c#

I wrote a class to automaticly translate text with selenium. When the translate button is pushed the page doesn't reload completly, I assume this happens with Javascript. I added a wait function to wait until the text shows up. However in 3 of the 10 generated translations I get the next error at line 30:
OpenQA.Selenium.WebDriverException: 'target frame detached (Session info: chrome=102.0.5005.115)'
Any solutions to fix it? thanks in advance!
class in c#
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System.Threading;
namespace WebscraperBasic
{
[Serializable]
public class vertalenNu
{
public static String translateText(IWebDriver driver, String text, String languageSource, String languageDestination)
{
// nl - en - de - fr -es -it
driver.Url = "https://www.vertalen.nu/zinnen/";
driver.FindElement(By.Id("vertaaltxt")).SendKeys(text);
SelectElement testt = new SelectElement(driver.FindElement(By.Id("tselectfrom")));
testt.SelectByValue(languageSource);
SelectElement test = new SelectElement(driver.FindElement(By.Id("tselectto")));
test.SelectByValue(languageDestination);
driver.FindElement(By.XPath("//input[#title='Vertaal']")).Click();
String technicalSheettext;
try
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));
wait.Until(driver => driver.FindElement(By.Id("resulttxt")).Text != "");
IWebElement technicalSheet = driver.FindElement(By.ClassName("mt-translation-content"));
technicalSheettext = technicalSheet.Text;
}
catch
{
technicalSheettext = "translation failed";
}
driver.Close();
driver.Quit();
return technicalSheettext;
}
}
}

How to Find the reCAPTCHA element and click on it in c# Selenium

Hello everyone I need some help. There is URL: http://lisans.epdk.org.tr/epvys-web/faces/pages/lisans/petrolBayilik/petrolBayilikOzetSorgula.xhtml. As you can see in screenshot I need to click checkbox Captcha.
https://i.stack.imgur.com/xjXaA.png
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace AkaryakitSelenium
{
class Program
{
private static string AkaryakitLink = "http://lisans.epdk.org.tr/epvys-web/faces/pages/lisans/petrolBayilik/petrolBayilikOzetSorgula.xhtml";
static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
driver.Navigate().GoToUrl(AkaryakitLink);
var kategoriCol = driver.FindElements(By.CssSelector(".ui-selectonemenu-trigger.ui-state-default.ui-corner-right"));
var x = kategoriCol[3];
x.Click();
var deneme = driver.FindElement(By.Id("petrolBayilikOzetSorguKriterleriForm:j_idt52_1"));
deneme.Click();
var check = driver.FindElement(By.Id("recaptcha-anchor"));
check.Click();
}
}
}
And lastly this error that I am facing:
"OpenQA.Selenium.NoSuchElementException: 'no such element: Unable to
locate element: {"method":"css
selector","selector":"#recaptcha-anchor"}"
Thank you for your help.
The element you are looking for is inside an iframe :
//iframe[#title='reCAPTCHA']
first you need to switch to iframe like this :
new WebDriverWait(driver, TimeSpan.FromSeconds(3)).Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.XPath("//iframe[#title='reCAPTCHA']")));
then you can perform a click on it :
var check = driver.FindElement(By.Id("recaptcha-anchor"));
check.Click();
PS : captchas are not meant to be automated. since Captcha stands for CAPTCHA stands for the Completely Automated Public Turing test to tell Computers and Humans Apart.
You can not bypass captcha with Selenium.
It is designed to avoid automated access to web pages as described here and in many other places.

How can I integrate selenium tests with sauce labs in c#?

On saucelabs website they provide a code snippet like this:
WebDriver webDriver = new WebDriver();
webDriver.set(new RemoteWebDriver(
new URL("https://UrlHEREagwgwgqwg4894+4+91gwgq")
))
When I add this to my tests, under WebDriver it says type or namespace 'WebDriver' could not be found. It is coming up for a namespace. For my Selenium tests I am using IWebDriver. I tried to change the WebDriver to IWebDriver and that didn't work. I also get the same error under the URL saying the namespace could not be found. For that one it does show for a namespace using System.Security.Policy; If I add that then I get an error under
new URL("https://UrlHEREagwgwgqwg4894+4+91gwgq")
Argument 1: cannot convert from 'System.Security.Policy.Url' to 'OpenQA.Selenium.DriverOptions'
This is how I am trying to use it. I was using ChromeDriver for my selenium tests but commented that part out to test on other browsers with saucelabs. This is my first time working with selenium/saucelabs so what I am doing my be completely off and I appreciate any advice.
[Fact]
public static void ClickDownloadButton()
{
WebDriver driver = new WebDriver();
driver.set(new RemoteWebDriver(
new Url("https://UrlHEREagwgwgqwg4894+4+91gwgq")
));
//using IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl(BaseUrl.downloadsUrl);
var login = new Login(driver);
login.EnterEmail();
login.EnterPassword();
login.HitSubmit();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
var downloadButton = wait.Until((d) => d.FindElements(By.LinkText("Download File")));
foreach (var button in downloadButton)
{
IWebElement element = wait.Until((d) => d.FindElement(By.LinkText("Download File")));
element.Click();
}
driver.Quit();
}
Here are the using statements:
using Xunit;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.IO;
using System.Security.Policy;
using OpenQA.Selenium.Remote;
Check out our demo C# repository with tons of examples.
Here's a working example that you can use from the following file:
using System;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;
namespace Selenium3.Nunit.Scripts.SimpleExamples
{
[TestFixture]
[Category("SimpleTest")]
public class SimpleSauceTest
{
IWebDriver _driver;
[Test]
public void SimpleTest()
{
//TODO please supply your Sauce Labs user name in an environment variable
var sauceUserName = Environment.GetEnvironmentVariable(
"SAUCE_USERNAME", EnvironmentVariableTarget.User);
//TODO please supply your own Sauce Labs access Key in an environment variable
var sauceAccessKey = Environment.GetEnvironmentVariable(
"SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);
ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability(CapabilityType.Version, "latest", true);
options.AddAdditionalCapability(CapabilityType.Platform, "Windows 10", true);
options.AddAdditionalCapability("username", sauceUserName, true);
options.AddAdditionalCapability("accessKey", sauceAccessKey, true);
options.AddAdditionalCapability("name", TestContext.CurrentContext.Test.Name, true);
options.AddAdditionalCapability("build", "ShwabTeamName:" + DateTime.Now, true);
_driver = new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"), options.ToCapabilities(),
TimeSpan.FromSeconds(600));
_driver.Navigate().GoToUrl("https://www.google.com");
Assert.Pass();
}
[TearDown]
public void CleanUpAfterEveryTestMethod()
{
var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
((IJavaScriptExecutor)_driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
_driver?.Quit();
}
}
}
Don't forget to install the correct Nuget packages so you have the corresponding resources. This is the minimum that you'll need:
<package id="Selenium.Support" />
<package id="Selenium.WebDriver" />
Side Note:
Don't use static methods as it'll make it impossible for you to parallelize.

addScriptToEvaluateOnNewDocument Selenium (Does not work)

I need to execute addScriptToEvaluateOnNewDocument method of Google Headless Chrome in C# .Net. I basically need to execute Javascript before any other javascript is executed on the documents. Here is my code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
namespace User
{
class Program
{
//public static IWebDriver driver = new ChromeDriver();
public static IWebDriver driver;
public static double magnification = 2;
static void Main(string[] args)
{
ChromeOptions options = new ChromeOptions();
//options.AddArgument("Page.addScriptToEvaluateOnNewDocument");
options.AddArgument("--window-size=1920,1080");
options.AddUserProfilePreference("Page.addScriptToEvaluateOnNewDocument", "alert('INJECTED SCRIPT')");
driver = new ChromeDriver(options);
var action = new OpenQA.Selenium.Interactions.Actions(driver);
System.Threading.Thread.Sleep(1000);
driver.Navigate().GoToUrl("https://google.com");
System.Threading.Thread.Sleep(10000);
}
}
}
But the alert isn't fired (i have tried other JavaScript code besides alert - nothing seems to work)
Try this.After initialize the driver.Hope this will work.
driver.ExecuteJavaScript("alert(0);")
OR
driver.Scripts().ExecuteScript("alert(0);")
I have only done this in Python but it should work the same way.
The chromedriver should expose a function named execute_cdp_cmd()
You can use this to run JavaScript before the page JavaScript is run. See the python example below. Note that you should add the code shown below after creating the driver but before you get the web page.
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
alert(0);
"""
})
I don't have a C# example, but this might help.
using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.DevTools.V91.Page;
using OpenQA.Selenium.Support.UI;
using RandomNameGeneratorLibrary;
using Network = OpenQA.Selenium.DevTools.V91.Network;
using DevToolsSessionDomains = OpenQA.Selenium.DevTools.V91.DevToolsSessionDomains;
IDevTools devTools = driver as IDevTools;
session = devTools.GetDevToolsSession();
var domains = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
domains.Page.AddScriptToEvaluateOnNewDocument(new AddScriptToEvaluateOnNewDocumentCommandSettings()
{
Source = jscode,
});

Screen Capture in C# using HtmlAgilityPack

Due to the lack of proper documentation, I'm not sure if HtmlAgilityPack supports screen capture in C# after it loads the html contents.
So is there a way I can more or less grab a screenshot using (or along with) HtmlAgilityPack so I can have a visual clue as to what happens every time I do page manipulations?
Here is my working code so far:
using HtmlAgilityPack;
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string urlDemo = "https://htmlagilitypack.codeplex.com/";
HtmlWeb getHtmlWeb = new HtmlWeb();
var doc = getHtmlWeb.Load(urlDemo);
var sentence = doc.DocumentNode.SelectNodes("//p");
int counter = 1;
try
{
foreach (var p in sentence)
{
Console.WriteLine(counter + ". " + p.InnerText);
counter++;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}
Currently, it scrapes and output all the p of the page in the console but at the same time I want to get a screen grab of the scraped contents but I don't know how and where to begin.
Any help is greatly appreciated. TIA
You can't do this with HTML Agility Pack. Use a different tool such as Selenium WebDriver. Here is how to do it: Take a screenshot with Selenium WebDriver
Could you use Selenium WebDriver instead?
You'll need to add the following NuGet packages to your project first:
Selenium.WebDriver
Selenium.Support
Loading a page and taking a screenshot is then as simple as...
using System;
using System.Drawing.Imaging;
using System.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
// Create a web driver that used Firefox
var driver = new FirefoxDriver(
new FirefoxBinary(), new FirefoxProfile(), TimeSpan.FromSeconds(120));
// Load your page
driver.Navigate().GoToUrl("http://google.com");
// Wait until the page has actually loaded
var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 10));
wait.Until(d => d.Title.Contains("Google"));
// Take a screenshot, and saves it to a file (you must have full access rights to the save location).
var myDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(Path.Combine(myDesktop, "google-screenshot.png"), ImageFormat.Png);
driver.Close();
}
}
}

Categories

Resources