Can I use a string variable when using LinkText? - c#

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.

Related

Unable to retrieve text of an element without tags in Selenium Webdriver

I am trying to retrieve the text of an element without a tag in Selenium C# but I am unable to do it. In the attached screenshot, I want to retrieve the text Adell Windler. I tried using Absolute XPath, Relative Xpath as well as cssSelector but the text that is getting retrieved is Name: . The Xpath that I used is:
IWebElement UsrNameText => Driver.FindElement(By.XPath("/html/body/app-root/app-user-detail/div[1]/div[1]/div[1]/div/div/div/div[2]/h5[1]"));
But instead of retrieving the whole "Name: Adell Windler", it is just retrieving the text "Name:". I even tried the text() method in the XPath but it is giving an error
"The result of the xpath expression .... is: [object Text]. It should be an element".
Screenshot of DOM Structure with web element
There is three scenarios :
Only name : : if you want to get "Name :" then create xpath for strong element.
"Name: Adell Windler" : if you need this one then create xpath of H5 element.
"Adell Windler" : if you need this one then create xpath of H5 and remove "Name :" from that string.
if you are facing issue then please revert on this one.

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

Selenium find element via Data-Qa attribute

I have building my Selenium framework. All the elements need to be found by Data-QA. I am unsure on how to do this. I have done the pervious using Ids that was simple enough. I cannot find data qa in the find element by
Would anyone be able to point me in the right direction.
It looks like you are attempting to find elements with a particular value for a specific attribute. I don't know C#, but with Python the following should work (I like to use a CSS selector):
all_login_inputs = find_elements_by_css_selector("input[data-qa='input_login_operator']")
this will return a list of elements that have a tag "input" with the "data-qa" attribute set to the value "input_login_operator"
It looks like there are extra single quotes in the HTML, inside the double quotes:
data-qa="'input_login_operator'"
I would remove the single quotes from the DOM, or escape them in the CSS selector.

Using Selenium to select an element with javascript in the href

I have a .NET WebForm and I need to click a link using Selenium and can't use the text content (because of translation issues). How can I identify this element?
registration form
I have tried the following, which does not work:
var element = Driver.FindElementsByXPath($"//*[#href='ctl01']");
The problem is that you are trying to look for an id within the xpath, while the element does not contain an id.
In this case, this should work:
var element = Driver.FindElementsByXPath($"//a[contains(text(), 'registration form')]");
This will only work if all the elements which you are trying to find are links with the text registration form in it.
If you want to find elements on the href, use:
var element = Driver.FindElementsByXPath
("//a[contains(#href, 'javascript:__doPostBack('ctl01','')')]");
Ultimately decided to identify within the href attribute by partial string:
.FindElementsByXPath($"//*[contains(#href, '{id}')]")
This is because putting the whole value of the javascript text into the Selenium call caused it to fail parsing.
try searching for the a href instead of the id like this:
a[#href='javascript:__doPostBack('ctl01','')']
with FindElementsByXPath
then on the var element try using SendKeys like so:
element.SendKeys(Keys.Enter);

How to give multiple arguments to find element by css selector

Hi I'm kind of new to selenium, so please bear with me if the question is too basic.
I wanna access a date picker element and choose a specific date.
I am trying to access the span element using both class and text inside.
I get an error of invalid string. Is the syntax below correct?
_driver.FindElement(By.CssSelector("span[class='xxx'][contains(text(),'xx')]"))
Looking at this cheatsheet
https://www.simple-talk.com/dotnet/.net-framework/xpath,-css,-dom-and-selenium-the-rosetta-stone/
I think it might be more like
_driver.FindElement(By.CssSelector("span.CCC:contains('TTT')"));
where CCC is your class name and TTT is the text your looking for.

Categories