解析HTML – 如何从标记中获取数字?
我正在开发一个与网站交互的Windows窗体应用程序。
使用WebBrowser
控件我控制网站,我可以使用以下方法遍历标记:
HtmlDocument webDoc1 = this.webBrowser1.Document; HtmlElementCollection aTags = webDoc1.GetElementsByTagName("a");
现在,我想从标签中获取特定文本,如下所示:
就像在这里一样,我希望在上面的标签中得到等于assignto的数字244并将其保存到变量中以供进一步使用。
我怎样才能做到这一点?
您可以尝试按’;’分割字符串 值,然后每个字符串’=’,如下所示:
string aTag = ...; foreach(var splitted in aTag.Split(';')) { if(splitted.Contains("=")) { var leftSide = splitted.Split('=')[0]; var rightSide = splitted.Split('=')[1]; if(leftSide == "assignedto") { MessageBox.Show(rightSide); //It should be 244 //Or... int num = int.Parse(rightSide); } } }
其他选项是使用Regexes,您可以在此处测试: https://www.regextester.com 。 有关正则表达式的更多信息: http : //msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx
希望能帮助到你!
如果所有情况都与此类似,并且您不介意在Windows窗体应用程序中引用System.Web
,那么tou可以执行以下操作:
using System; public class Program { static void Main() { string href = @"issue?status=-1,1,2,3,4,5,6,7& @sort=-activity&@search_text=&@dispname=Show Assigned& @filter=status,assignedto&@group=priority& @columns=id,activity,title,creator,status&assignedto=244& @pagesize=50&@startwith=0"; href = System.Web.HttpUtility.HtmlDecode(href); var querystring = System.Web.HttpUtility.ParseQueryString(href); Console.WriteLine(querystring["assignedto"]); } }
这是一个简化的示例,首先需要提取href
属性文本,但这不应该很复杂。 拥有href
属性文本可以利用基本上是查询字符串并在.NET中重用已经解析查询字符串的代码。
要完成该示例,要获取href
属性文本,您可以执行以下操作:
上述就是C#学习教程:解析HTML – 如何从标记中获取数字?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
HtmlElementCollection aTags = webBrowser.Document.GetElementsByTagName("a"); foreach (HtmlElement element in aTags) { string href = element.GetAttribute("href"); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1006626.html