Using variables as selectors with Selenium 2 Webdriver by.cssselector - c#

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

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();

Can I use a string variable when using LinkText?

Using Selenium in Visual Studio. I'm trying to click on a item in a list. The item has a unique ID.
CA-41107005-00000040
Instead of referring to the actual ID-number I want to make the test more dynamic by referring to a string variable that will store a item ID. I call this variable: changeActionNumber
The HTML code for the item looks like this:
I have tried clicking on the item like this:
wait.Until(ExpectedConditions.ElementToBeClickable(By.LinkText($"{changeActionNumber}"))).Click();
And also like this:
wait.Until(ExpectedConditions.ElementToBeClickable(By.LinkText(changeActionNumber))).Click();
But both cases gave the same error:
Message: OpenQA.Selenium.WebDriverTimeoutException : Timed out after 10 seconds
----> OpenQA.Selenium.NoSuchElementException : no such element: Unable to locate element: {"method":"link text","selector":"CA-41107005-00000040"}
(Session info: chrome=77.0.3865.75)
Is it not possible to use variables when using LinkText?
Try the below xapth
wait.Until(ExpectedConditions.ElementToBeClickable(By.Xpath("//a[text()='" +changeActionNumber + ']"))).Click();
OR
wait.Until(ExpectedConditions.ElementToBeClickable(By.Xpath("//a[contains(.,'" +changeActionNumber + ')]"))).Click();
AFAIK, LinkText selector looks for link text as it is presented on page, not in html code. So if this text is additionally formatted before being displayed on page, like letters to lower case or special symbols removed, you must consider this.
If you want to work with text as it presented in code, try xpath instead
By.XPath(string.Format(".//a[.='{0}']", changeActionNumber))
Using variables in LinkText was not the problem.
The problem was that my driver was not focused on the correct iframe and could therefore never find a matching LinkText value.
I changed my iframe focus like this:
driver.SwitchTo().DefaultFrame();
driver.SwitchTo().Frame("firstiframe");
driver.SwitchTo().Frame("secondiframe");
driver.SwitchTo().Frame("thirdiframe");
driver.SwitchTo().Frame("ECMMyChangeActions");
And after that I could use LinkText with a variable without any problem.

Using variables within a string - WebDriver 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.

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.

Ranorex API can't find a web element which Ranorex Spy finds

I try to find a table row.
First, I used Ranorex Spy, and try to use the following rXpath expression:
/dom[#domain='127.0.0.1']//table//td[#innertext='john.doe#acme.com']/../following-sibling::tr/.[1]
Ranorex Spy finds and highlights this tag successfully. But when I'm trying to find thiselement using Ranorex API, it returns no results. The code is following
// path is exactly rXpath expression which is used for Ranorex Spy
IList<Ranorex.Core.Element> elements = Host.Local.Find(path);
Can you tell me, where is my mistake or are there any issues with rXpath?
Actually it's not a solution, but a workaround.
The following XPath retrieves a specific entry from . And [1] is an index of a desired element
/dom[#domain='127.0.0.1']//table//td[#innertext='john.doe#acme.com']/../following-sibling::tr/.[1]
So, the idea is to obtain all elements as a collection, and to use element with an appropriate index.
String tableRowShortXpath = "/dom[#domain='127.0.0.1']//table//td[#innertext='john.doe#acme.com']/../following-sibling::tr";
IList<Ranorex.WebElement> elements = Ranorex.Host.Local.Find<Ranorex.WebElement>(tableRowShortXpath);
Ranorex.WebElement desiredElement = elements[rowIndex - 1];
For my purposes it's enough, though it works 2 times slower if the element was found with direct XPath query.

Categories