我有一些测试 html 页面
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Page for test</title>
</head>
<body>
<div class="r_tr">
<span class="r_rs">Inner text<span class="otherSpan" style="display: none">text</span></span>
</div>
</body>
</html>
我想获得“内部文字”。我正在使用 HtmlAgilityPack。我写这个方法
public string GetInnerTextFromSpan(HtmlDocument doc)
{
const string rowXPath = "//*[@class=\"r_tr\"]";
const string spanXPath = "//*[@class=\"r_rs\"]";
string text = null;
HtmlNodeCollection rows = doc.DocumentNode.SelectNodes(rowXPath);
foreach(HtmlNode row in rows)
{
text = row.SelectSingleNode(spanXPath).InnerText;
Console.WriteLine("textL {0}", text);
}
return text;
}
但此方法返回“内部文本”。我写了一些单元测试来解释我的问题
[Test]
public void TestGetInnerTextFromSpan()
{
var client = new PromtTranslatorClient();
var doc = new HtmlDocument();
doc.Load(@"testPage.html");
var text = client.GetInnerTextFromSpan(doc);
StringAssert.AreEqualIgnoringCase("Inner text", text);
}
和结果
Expected string length 10 but was 14. Strings differ at index 10.
Expected: "Inner text", ignoring case
But was: "Inner texttext"
---------------------^