Using variables within a string - WebDriver C# - c#

I am trying to use a common string as a variable to make my code more concise, but Selenium WebDriver keeps throwing the following exception:
OpenQA.Selenium.WebDriverTimeoutException InvalidSelectorException: invalid selector: An invalid or illegal selector was specified
I thought it could be done with string interpolation as follows:
string common = "\"[data - test - code ^= 'ABC'] > ";
new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(2)).Until(ExpectedConditions.ElementIsVisible((By.CssSelector($"{common}td.result__td.result__td--test > img"))));
...but no joy. Any ideas?
Thanks

Selenium can't handle attributes like data - test - code. data-test-code for example (without spaces) would be acceptable. You need to find another way to locate that element.
By the way, you have a redundant " in the beginning of the selector.

Related

OpenQA.Selenium.InvalidSelectorException: 'invalid selector: An invalid or illegal selector was specified error in Selenium

I am using chromedriver in CS to find an element using css selector however I receive the following error:
OpenQA.Selenium.InvalidSelectorException: 'invalid selector: An invalid or illegal selector was specified
My code:
var body = driver.FindElementsByCssSelector(".add-to-cart.float-right.font-montserratSemiBold.text-11.lg:text-12.text-secondary.flex.flex-wrap.leading-articlesmall");
I am trying to find the element of the Add to basket buttons on this website
What is wrong with my selector and how can I resolve this issue?
This error message...
OpenQA.Selenium.InvalidSelectorException: 'invalid selector: An invalid or illegal selector was specified
...implies that the WebDriver instance was unable to locate the desired WebElement was invalid.
The css-selectors was almost perfect but the issue was with : as in lg:text-12. The character : have a special effect when used within a css-selectors as it is used in a couple of css-selectors variants. A few examples:
input:enabled
p:first-child
p:first-of-type
:not(p)
p:nth-child(2)
p:nth-last-of-type(2)
Solution
There are two solutions.
In the first approach you can escape the : character.
In the second and the most effective approach instead of mentioning all the class attributes, you can use a single static classname which identifies all the elements with text as Add to basket as follows:
css-selectors:
button.add-to-cart
xpath
//button[contains(#class, 'add-to-cart')]
Snapshot:
References
You can find a couple of relevant detailed discussions in:
Python: find_element_by_css_selector
Try this selector:
var body = driver.FindElementsByCssSelector(".add-to-cart");
Please try adding double backslashes escape character before : in lg:text-12 as shown below
var body = driver.FindElements(By.CssSelector(".add-to-cart.float-right.font-montserratSemiBold.text-11.lg\\:text-12.text-secondary.flex.flex-wrap.leading-articlesmall"));
Tested this in my local and worked fine returning eleven elements.
You can use findelements method in selenium
List<WebElement> products=driver.findElements(By.xpath("//button[contains(text(),'Add to basket')]"));
// if you want to pick 1 st product you can use below code
products.get(0).click();

C# mongodb parsing "+" - Quantifier{x,y} following nothing

I am getting the above error when trying to search a field in mongodb collection using C# driver.
Below is the line of code where i am getting this error:
IMongoQuery query = Query.Matches(field, BsonRegularExpression.Create(
new Regex(searchCri, RegexOptions.IgnoreCase)));
I tried replacing the searchCri variable with Regex.Replace(searchCri, "[~#%&*{}/<>?|\"-]+", "") however it did not fix my problem.
Could anyone assist?
This error occurs because the searchCri starts with + or is following a non-quantifiable subpattern.
You need to implement Regex.Escape and use something like:
new Regex(Regex.Escape(searchCri), RegexOptions.IgnoreCase)

Adding string variable to xpath c# selenium

I have probably spent a good 8 hours trying to figure this out but am constantly failing. I have searched an age for a solution
I am trying to find an selenium element by partial id match using xpath (c# selenium libraries). The following works perfectly fine. The partial text is sel_1-rowse1
IWebElement elem = wait5.Until(x => x.FindElement(By.XPath("//a[contains(#id,'sel_1-rowsel')]")));
However when I want to use a variable named partial this does not work
string partial = "sel_1-rowse1";
IWebElement search = wait.Until(x => x.FindElement(By.XPath(String.Format("//a[contains(#id,'{0}')]", partial))));
or
IWebElement search = wait.Until(x => x.FindElement(By.XPath(String.Format("//a[contains(#id,{0})]", partial))));
I have tried single quotes double quotes and escape chars. But cant figure this out. I cant even provide the error as its picking up a valid id. Brain is severely depleted on this one.
Just an observation, the first example element id ends with lower case 'L' (so l) while the second one with number 1. Might be just a copy paste error but worth asking...
partial is a reserved keyword in C#.
Refactor partial to something else (not reserved by C#) and you should be golden.

Finding an element by partial id with Selenium in C#

I am trying to locate an element with a dynamically generated id. The last part of the string is constant ("ReportViewer_fixedTable"), so I can use that to locate the element. I have tried to use regex in XPath:
targetElement = driver.FindElement(
By.XPath("//table[regx:match(#id, "ReportViewer_fixedTable")]"));
And locating by CssSelector:
targetElement = driver.FindElement(
By.CssSelector("table[id$='ReportViewer_fixedTable']"));
Neither works. Any suggestions would be appreciated.
That is because the css selector needs to be modified you were almost there...
driver.FindElement(By.CssSelector("table[id*='ReportViewer_fixedTable']"))`
From https://saucelabs.com/blog/selenium-tips-css-selectors-in-selenium-demystified:
css=a[id^='id_prefix_']
A link with an id that starts with the text id_prefix_.
css=a[id$='_id_sufix']
A link with an id that ends with the text _id_sufix.
css=a[id*='id_pattern']
A link with an id that contains the text id_pattern.
You were using a suffix which I'm assuming was not the partial link text identifier you were supposed to be using (unless I saw your html, which means try showing your html next time). *= is reliable in any situation though.
try using
targetElement = driver.FindElement(By.XPath("//table[contains(#id, "ReportViewer_fixedTable")]"));
Note this will check for all the elements that have id which contains (and not only ends with 'ReportViewer_fixedTable'). I will try to find a regex option that would be more accurate answer to you question.
This solution will work irrespective of the XPath version. First, create a method somewhere in your COMMON helper class.
public static string GetXpathStringForIdEndsWith(string endStringOfControlId)
{
return "//*[substring(#id, string-length(#id)- string-length(\"" + endStringOfControlId + "\") + 1 )=\"" + endStringOfControlId + "\"]";
}
In my case, below is the control ID in different version of my product ::
v1.0 :: ContentPlaceHolderDefault_MasterPlaceholder_HomeLoggedOut_7_hylHomeLoginCreateUser
v2.0 :: ContentPlaceHolderDefault_MasterPlaceholder_HomeLoggedOut_8_hylHomeLoginCreateUser
Then, you can call the above method to find the control which has static end string.
By.XPath(Common.GetXpathStringForIdEndsWith("<End String of the Control Id>"))
For the control ID's which I mentioned for v1 & v2, I use like below :
By.XPath(Common.GetXpathStringForIdEndsWith("hylHomeLoginCreateUser"))
The overall logic is that, you can use the below XPath expression to find a control which ends with particular string:
//*[substring(#id, string-length(#id)- string-length("<EndString>") + 1 )="<EndString>"]

Using variables as selectors with Selenium 2 Webdriver by.cssselector

I am using Visual Studio 2010 to write Selenium 2 Webdriver automated tests in C#.
I have searched high and low for examples of using variables as selectors and have found nothing that seems to work. The one example I have found of a variable used as a selector had the variable with $ prefix and enclosed in {}.
An example of what I am trying to do is below:
string surveyName = "Selenium test survey";
Driver.FindElement(By.CssSelector("tr[svd='${surveyName}']"))
I get the error:
OpenQA.Selenium.WebDriverException : Unexpected error. Unable to find element using css: tr[svd='${surveyName}']
If I 'hard code' the selector like this:
Driver.FindElement(By.CssSelector("tr[svd='Selenium test survey']"))
it finds the element.
svd is an attribute of the tr element. I am trying to select a row within a table by the value of this attribute. The text will be different for each test and so must be a variable.
I have tried expressing the variable a number of different ways but had no luck making this work. Any help would be much appreciated.
Thanks.
string surveyName = "Selenium test survey";
Driver.FindElement(By.CssSelector(String.Format("tr[svd='{0}']", surveyName))
will do what you want. This is c# so when it takes a string you can do all kinds of things to get that string

Categories