How to write xpath for the below HTML:
<span id="filename_548948">Test DC Email </span>
The following xpath doesn't seem to work:
Driver.FindElement(By.XPath(".//span[text() = '" + nameOfEmail + "']")).Click();
The solution depends on what the string nameOfEmail contains.
You have an xpath query on exact text. Meaning every character should be the same in the search as on the webpage.
So if string nameOfEmail = "Test DC Email "
It will search properly.
Also, losing the . in front of the // might help
As per the HTML you have shared you can use the following xpath :
//with a constant string
Driver.FindElement(By.XPath("//span[starts-with(#id,'filename_') and contains(normalize-space(), 'Test DC Email')]")).Click();
//with a variable string
Driver.FindElement(By.XPath("//span[starts-with(#id,'filename_') and contains(normalize-space(), '" + nameOfEmail + "')]")).Click();
Related
I need to get some text from a website we are using to get our data from. I finally found how, using HtmlAgilityPack and finding the Xpath I'm able to print out some text from the website.
But when I try to print the date and kind, which is coded like this:
<span class="span-line-break">zaterdag 05 december 2020</span> //Date
<span class="afvaldescr">Papier en karton</span> //Kind
I can't reach these two strings using my current code:
public string Postalcode = "6093DK";
public string Number = "2";
public string Add = "";
string url = "https://mijnafvalwijzer.nl/nl/" + Postalcode + "/" + Number + "/" + Add;
var web = new HtmlAgilityPack.HtmlWeb();
HtmlDocument doc = web.Load(url);
string when = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]/div/table[1]/tbody/tr/td[1]/a/p/span[1]")[0].InnerText;
string what = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]/div/table[1]/tbody/tr/td[1]/a/p/span[2]")[0].InnerText;
textBox1.Text = when;
textBox2.Text = what;
I figured that because the text is in a class I can not reach it.
Can someone help me find a more specific route to these strings?
The website is a Dutch garbadge calendar, don't mind it.
Browser inserts tbody for table element although it is not present in html. So here I just removed tbody from your XPath. In Chrome you can use network tab for viewing original response
string when = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]/div/table[1]/tr/td[1]/a/p/span[1]")[0].InnerText;
string what = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]/div/table[1]/tr/td[1]/a/p/span[2]")[0].InnerText;
You can also use shortened version of XPath using "//" and class selectors
string when = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]//table[1]//span[#class=\"span-line-break\"]")[0].InnerText;
string what = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]//table[1]//span[#class=\"afvaldescr\"]")[0].InnerText;
Hi I have the following line:
var table = #"<table id=""table_id"" class=""display"">
which is building a table and continues on the next line but I'm just trying to append a string at the end of table_id :
var table = #"<table id=""table_id" + instance + """ class=""display"">
so the final output (if instance = 1234) should be:
<table id="table_id1234" class="display">
But I think the quotes are throwing it off. Any suggestions on how t achieve the last line?
Thanks
A string.Format method placeholder is enough to concatenate instance without cutting through quote signs ({0} is the placeholder):
var table = string.Format(#"<table id=""table_id{0}"" class=""display"">", instance);
Or you can use escape sequence \" for escaping quotes without string literal:
var table = "<table id=\"table_id" + instance + "\" class=\"display\">"
Result:
<table id="table_id1234" class="display">
Demo: .NET Fiddle
Try to use escape character for double quote(\") using this code:
var id = "1234";
var table = "<table id=\"table_id" + id + "\" class=\"display\">";
Here is an online tool for converting string to escape/unescape:
https://www.freeformatter.com/java-dotnet-escape.html
So you can copy the result and place your variables.
I think the best idea and newest idea for this situation is $ sign before your text and with this sign you dont need to extra sign in your string
example
vat table = $"<table id='table_id{instance}' class='display'">
# is used to escape double quotes from one string but in your example, you are actually concatenating three different strings, soyou should escape the third string as well like this:
var table = #"<table id=""table_id" + instance + #" "" class=""display"" >";
Alternatively, you could also use the StringBuilder class which is more memory efficient and might make your strings easier to read.
I think I can't see the forest for the trees here. I want to write a string. Using Linq to SQL I have created a result and I'm looping through it to dynamically write anchor tags.
But, the code is producing this:
<a 45="" href="ADappointment.aspx?openingid">My person booked< /a >
I want:
<a href="ADappointment.aspx?openingid=45">My person booked< /a >
Here's what I'm doing:
foreach (var anOpening in results)
string sFlag = #"";
sFlag = #"<td>" + patient.FirstName + " " + patient.LastName + " accepted </td>";
...
What am I doing wrong?
You have quotes in your href value the browser doesnt expect.. so it is rendering it completely incorrectly.
You are producing this:
href="urlhere.aspx?id="99""
Note the quotes around the ID. Remove those from your code. You want something like this:
sFlag = #"<td><a href=""ADappointment.aspx?openingid=" + anOpening.OpeningId + """>" + /* the rest here */
Ideally you would use a library to do this. There is a TagBuilder class in the MVC assembly.
Use String.Format to clearly format string.
foreach (var anOpening in results)
{
var sFlag = String.Format(#"<td>{1} {2} accepted </td>", anOpening.OpeningId, patient.FirstName, patient.LastName);
}
I need to pass a URL from C# to javascript. The problem is if the filename has single quote, it does not execute the javascript. When I use HttpUtility.HtmlEncode(fileNameWithoutEx) it does execute javascript but if filename is say "Copy of David's Birth Certificate" then URL gets converted to ?View.aspx?length=60&ext=pdf&file=Copy of David' Birth Certificate.
When View.aspx tries to get the querystring file i.e; filename, it gets set to "Copy of David" and not "Copy of David's Birth Certificate". Because of & it does not get the rest of the querystring.
if (System.IO.File.Exists(fileLocation)) {
string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(fileLocation);
string fileExtension = System.IO.Path.GetExtension(fileLocation).Replace(".", "");
string title = System.IO.Path.GetFileNameWithoutExtension(fileName);
string url = "View?length=" + 60+ "&ext=" + fileExtension + "&file=" + fileNameWithoutExt;
ScriptManager.RegisterStartupScript(this, GetType(), "ShowPDF", "$(document).ready(function(){ShowPDFDocument('" + title + "', '" + url + "');});", true);
}
How can I send url with single quote to javascript?
What's the best way to handle ' and other special characters?
Use Uri.EscapeDataString(yourLinkHere);. See Uri.EscapeDataString on MSDN.
You're embedding the title and URL within quote-delimited strings in JavaScript, so you need to escape them.
title = title.Replace("'","\\'");
url = url.Replace("'","\\'");
You can try percent codes. I would recommned using %20 in the place of spaces as well. You can chance the file name itself or the way you route to it in code.
urlstring.replace("'", "%27")
Try to replace your ' with %27 which is the standard percent encode for '
Characters with reserved purposes should be replaced to guarantee functionality in all environments. You can view the list and read up on this here.
I don't know what is wrong with the following string:
"Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
I can't get the concatenated string. I am getting Report(29-Dec-2009. That's all and
the rest gets left out from the string.
What is the reason?
Try this:
string filename =
String.Format(
"Report({0:dd-MMM-yyyy} to {1:dd-MMM-yyyy})",
System.DateTime.Now, System.DateTime.Now.AddMonths(-1));
EDIT: Since in your download box you got your filename broken in first whitespace, you could to try ONE of these:
filename = HttpUtility.UrlEncode(filename); // OR
filename = """" + filename + """";
Seems some browsers doesn't handles whitespaces very nicely: Filenames with spaces are truncated upon download. Please check it you can to download other filenames with whitespace in other sites.
You need to assign it to something:
string s = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
Update: I just saw your update to the question. How are you displaying the string? I'm guessing that you are displaying it in a GUI and the label is too short to display the complete text.
Try this:
string newstring =
string.Format(
"Report ({0} to {1})",
System.DateTime.Now.ToString("dd-MMM-yyyy"),
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
);
What are you assigning the result to? It would be easier to read the code if you used string.Format
You are not assigning the concatenated result to anything, so can't use it:
string myConcatenated = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + ")";
Using this code...
string test = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " +
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")";
I saw the following result.
Report(29-Dec-2009 to 29-Nov-2009)
It could be that the string is being truncated later on. Make sure that you set a breakpoint right after this code is run and check the value of the variable to which it is assigned (test in my case).
If, as in your previous question, you are using this value to create a file, it may be that it's the space before "to" that is causing the problem. Try to use:
"Report("
+ System.DateTime.Now.ToString("dd-MMM-yyyy")
+ "To"
+ System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
+ ")"
instead and see if that fixes it.
If that does fix it, you'll probably need to either figure out how to quote the entire file name so it's not treated as the three separate arguments, "Report(29-Dec-2009", "to" and "29-Nov-2009)". Or simply leave your reports names without spaces.
I'd choose the latter but then I'm fundamentally opposed to spaces in filenames - they make simple scripts so much harder to write :-)