Is it possible to display the text associated with a specific element? - c#

I have been working with selenium and C#, and I am wondering if I can return the text associated with a specific element.
For example, here is the line of HTML that contains what I want to display:
<span class="field">1149156-1</span>
Would it be possible to save the "1149156-1" in a string to use for later?
I have tried the following code, but it returns a strange value, definitely not the value I want it to return:
string testvariable = driver.FindElement(By.XPath("/html/body/div/div[4]/div[2]/form/div[2]/div/table/tbody/tr[2]/td[1]")).ToString();
Hope I provided enough information!

You can just use webElement.Text.
string testvariable = driver.FindElement(By.XPath("/html/body/div/div[4]/div[2]/form/div[2]/div/table/tbody/tr[2]/td[1]")).Text;
On another note -- I recommend using relative XPath syntax instead of absolute, and querying on WebElement attributes such as id, name, and class to get more accurate locators.
For example, the XPath in the example you provided can be re-written more robustly as such:
//table[#id='someId']/tbody/tr[2]/td[1]

Related

How to get a span's text that contains "&nbsp" using Selenium

I am using Selenium ChromeDriver. I have a problem obtaining the contents of a span as defined in the screen shot below:
I tried:
var text = element.Text;
but it returns an empty string.
The span's text is: "Yes, we can both go."
How can I get the span's text?
Edited to reflect updates in the comments
Because it's a span, which behaves much like a div element, there's no inherent text or value attribute at play--it's a container, and you'll need to grab the value from inside the span container (see this answer and this article). Based on the fact you want the actual string value and not the html, the "textContent" attribute is probably the best bet.
You can use Selenium's "GetAttribute" method to get the "textContent" attribute of the span:
var textValue = element.GetAttribute("textContent");
// do code against textValue
There's no direct get accessor built into the Element class for attributes, so you'll need to pass in the string value for the name of the attribute you want, and it'll return the value if it's present.

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

Can't get span text using csspath

Im querying a span element (without class, id, or anything) using csspath in selenium c# but the text attribute is empty.
what's happening and how can I get the text within the span?
So the DOM structure is:
/div/div/ul/li/a/span
Query is:
driver.FindElement(By.CssSelector(".contactActions .iconActions .icon .privacy span"));
You could probably try
driver.FindElement(By.XPath("//div[#id='otherOuterDiv']//span"));
I usually use relative XPaths, because I find it easier to specify them.
Solution is:
string text = driver.FindElement(By.CssSelector(".contactActions .iconActions .icon .privacy span")).GetAttribute("textContent"));

How can I parse the information from this XML?

this is an example of the XML I want to scrape:
http://www.dreamincode.net/forums/xml.php?showuser=335389
Notice that the contactinformation tag has many contact elements, each similar but with different values.
For example, the element that has the AIM content in it, how can I get the content of the Value tag that's in the same family as the AIM content element?
That's where I'm stuck. Thanks!
Basically: I need to find the AIM content tag, make a note of where it is, and find the Value element within that same family. Hope this makes the question clearer
LINQToXML
var doc = XDocument.Load(#"http://www.dreamincode.net/forums/xml.php?showuser=335389");
var aimElements = doc.Descendants("contact").Where(a=>a.Element("title").Value == "AIM").Select(a=>a.Element("value").Value);
this will give you a list of strings that hold the value of the value element for a contact that has the title AIM, you can do a First() or a FirstOrDefault if you believe there should only be 1
Using an xpath like the one below will get you the contact/value node where contact/title is "AIM":
/ipb/profile/contactinformation/contact[title='AIM']/value
Have you tried to parse the XML rather than "scraping" it?

XPATH query, HtmlAgilityPack and Extracting Text

I had been trying to extract links from a class called "tim_new" . I have been given a solution as well.
Both the solution, snippet and necessary information is given here
The said XPATH query was "//a[#class='tim_new'], my question is, how did this query differentiate between the first line of the snippet (given in the link above and the second line of the snippet).
More specifically, what is the literal translation (in English) of this XPATH query.
Furthermore, I want to write a few lines of code to extract the text written against NSE:
<div class="FL gL_12 PL10 PT15">BSE: 523395 | NSE: 3MINDIA | ISIN: INE470A01017</div>
Would appreciate help in forming the necessary selection query.
My code is written as:
IEnumerable<string> NSECODE = doc.DocumentNode.SelectSingleNode("//div[#NSE:]");
But this doesnt look right. Would appreciate some help.
The XPath in the first selection reads "select all document elements that have an attribute named class with a value of tim_new". The stuff in brackets is not what you're returning, it's the criteria you're applying to the search.
I don't have the HTML Agility pack, but if you are trying to query the divs that have "NSE:" as its text, your XPath for the second query should just be "//div" then you'll want to filter using LINQ.
Something like
var nodes =
doc.DocumentNode.SelectNodes("//div[text()]").Where(a => a.InnerText.IndexOf("NSE:") > -1);
So in English, "Return all the div elements that immediately contain text to LINQ, then check that the inner text value contains NSE:".
Again, I'm not sure the syntax is perfect, but that's the idea.
The XPath "//div[#NSE:]" would return all divs that have and attribute named, NSE:, which would be illegal anyway because ":" isn't allowed in an attribute name. Youre looking for the text of the element, not one of its attributes.
Hope that helps.'
Note: If you have nested divs that both contain text as in <div>NSE: some text<div>NSE: more text</div></div> you're going to get duplicate results.

Categories