Using Selenium to select an element with javascript in the href - c#

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

Related

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.

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.

Parsing xml tags with colons inside using C#

I'm working in Xamarin on one android app which is parsing xml from this webiste: http://video.cazin.net/rss.php, and populate listview and in particular I have a problem getting value from this tag:
<media:thumbnail url="http://video.cazin.net/uploads/thumbs/2d07f1e49-1.jpg" width="480" height="360"/>
I created namespace:
xmlNameSpaceManager.AddNamespace("ab", "http://search.yahoo.com/mrss/");
and than tried to get value from url attribute:
XmlNodeList xmlNode = document.SelectNodes("rss/channel/item");
if (xmlNode[i].SelectSingleNode("//ab:thumbnail[#url='http://video.cazin.net/rss.php']", xmlNameSpaceManager) != null)
{
var thumbnail = xmlNode[i].SelectSingleNode("//ab:thumbnail=[#url='http://video.cazin.net/rss.php']", xmlNameSpaceManager);
feedItem.Thumbnail = thumbnail.Value;
}
I also tried something like this:
//ab:thumbnail/#url
but than I got value of just first image. I'm sure the problem is here somewhere because I have the same code parisng images from another xml tag without colon inside and it's working correctly. Does anyone had similar experience and knows what I should put in those braces? Thanks
Your current query is searching for a thumbnail element where the url attribute is equal to http://video.cazin.net/rss.php - there are none that match this.
Your 'I also tried' query of //ab:thumbnail/#url is closer, but the // means that the query will start from the root of the document, so you get the all urls (but you only take the first).
If you want the element that matches taking the current node context into consideration, you need to include the current node context in the query - this is represented by .. So .//ab:thumbnail/#url would find all url attributes in a thumbnail element contained by the current node. You can see the result in this fiddle.
I would strongly suggest you use LINQ to XML instead, however. It's a lot nicer to work with than the old XmlDocument API. For example, you could find all item thumbnail urls using this code:
var doc = XDocument.Load("http://video.cazin.net/rss.php");
XNamespace media = "http://search.yahoo.com/mrss/";
var thumbnailUrls = doc.Descendants("item")
.Descendants(media + "thumbnail")
.Attributes("url");

Combining Regex with Selenium in C#

I have a Automation Suite, currently testing against Wordpress (a test site to practice against). I am attempting to verify when a user edit's an existing Page they are taken to the correct screen. Previously the following code snippet was working fine, however now the ID mentioned below is no longer present (it was an image).
public static bool IsInEditMode()
{
return Driver.Instance.FindElement(By.Id("icon-edit-pages")) != null;
}
Assert.AreEqual(NewPostPage.IsInEditMode(), "You are not in edit mode");
The HTML I am targeting is...
<h2>
Edit Page
Add New
</h2>
I would like to extract the value of the h2 tag 'Edit Page'. Currently I am also getting the value of the anchor 'Add New', which I need to ignore.
using a CssSelector with "h2:first-child" returns both values.
I think I need to use a regular expression, if anyone has any suggestions to help that would be great.
I attempted doing something similar in JSFiddle but require the C# equivalent
var myString = document.getElementsByTagName('h2')[0].innerHTML;
var newString = myString.replace(/<([^>]+?)([^>]*?)>(.*?)<\/\1>/ig, "");
console.log(newString);
You can also get the parent element's text and remove the child element's text from it:
var parent = Driver.FindElement(By.TagName("h2"));
var child = parent.FindElement(By.TagName("a"));
var text = parent.Text.Replace(child.Text, "").Trim();
You can use StringAssert to verify if the string to check contains the expected string. I think is better because you not need to use regex
Example:
StringAssert.Contains(message, expectedmessage);

Select "src" value with XPath to HtmlAgilityPack

I'm on a development process of a crawling engine. My program crawls websites through Xpath with HtmlAgilityPack. I need to get some image src tag's directly. You can see my simple code below which is not working correctly, thanks in advice!
PS: Please ignore " char problem, XPath patterns are provided by database.
Agility.DocumentNode.SelectSingleNode("//img[#id="product_photo"]/#src");
And this is the line i need to crawl (the *...* part shows block to extract
<img id="product_photo" src="*/images/thumb/4400/10280/st.jpg*">
Some pages provide image in meta tags so .Attributes["src"] wont work.
UPDATE: You can see my query and result here
You cann't get the value of "src" or any other attributes in using:
Agility.DocumentNode.SelectSingleNode(yourXpath);
Just by using:
string s=Agility.DocumentNode.SelectSingleNode(yourXpath).value;
It's because XPath cann't return value of an attribute by SelectSingleNode() func in HtmlAgilityPack class. So you must use SelectSingleNode(yourXpath).value or use Regex after the pharsing to get just the "src" without the outerText.

Categories