提问人:medpicz 提问时间:5/9/2021 最后编辑:Bruno Canettierimedpicz 更新时间:5/10/2021 访问量:124
如何在 c# 代码中使用 indexof 从 HTML 解析/获取参数及其值
How to parse / get Parameter and its value from an HTML using indexof in c# code
问:
如何使用 indexof 方法以编程方式从 c# 中的 HTML 字符串中检索子字符串。 这里 String HTML 是 html 的全部内容,并希望从 parseString 中检索 Admission date 值。现在,此代码从 HTML 返回了错误的内容。有人可以在我的代码中找出问题吗?
protected string ParseAdmissionDate(string Html)
{
string parseString = "<TD style=\"HEIGHT: 5.08mm; \" class=\"a355c\"><DIV class=\"a355\">AdmissionDate</DIV></TD><TD class=\"a359c\"><DIV class=\"a359\">3/8/2021</DIV></TD>";
int i = 0;
i = Html.IndexOf(parseString, 0, Html.Length);
if (i > 0)
{
i += parseString.Length;
int end = Html.IndexOf("</TD>", i, (Html.Length - i));
return Html.Substring(i, end - i);
}
else
return null;
}
答:
0赞
Bruno Canettieri
5/10/2021
#1
您应该考虑使用像 HtmlAgilityPack 这样的库或进行 Web 抓取。
如果你真的想使用 IndexOf(出于未知原因),你必须记住 0 是一个有效的结果(意味着你在索引 0 上找到了子字符串),它会是这样的
public static string ParseAdmissionDate(string Html)
{
//html contains approximately
//<TD style=\"HEIGHT: 5.08mm; \" class=\"a355c\"><DIV class=\"a355\">AdmissionDate</DIV></TD><TD class=\"a359c\"><DIV class=\"a359\">3/8/2021</DIV></TD>
//Find Div of the AdmissionDate
var searchPattern = ">AdmissionDate</DIV>";
var searchIndex = Html.IndexOf(searchPattern, StringComparison.InvariantCultureIgnoreCase);
if(searchIndex < 0) return null;
//Get the string that is after the searchString
var stringAfterSearchPattern = Html.Substring(searchIndex + searchPattern.Length);
//Get the next close div after the searchString
var endIndex = stringAfterSearchPattern.IndexOf("</DIV>", StringComparison.InvariantCultureIgnoreCase);
if(endIndex < 0) return null;
//Index of the opening div
var startValueIndex = stringAfterSearchPattern.Substring(0, endIndex).LastIndexOf(">");
if(startValueIndex < 0) return null;
return stringAfterSearchPattern.Substring(startValueIndex + 1, endIndex - startValueIndex - 1);
}
问题是,如果 html 略有更改,例如,如果 AdmissionDate 不在 div 中(类似于“<td>AdmissionDate</td>”),该方法将失败。 因此,我指示网络抓取库。
评论
0赞
DisappointedByUnaccountableMod
5/10/2021
仅供参考,它是刮擦(刮擦,刮刀,刮擦)而不是报废
0赞
medpicz
5/11/2021
@Bruno Canettieri 这正在按预期工作。
评论