我遇到了一些奇怪的事情,我想听听你的意见。
有一个网页,其中包含 span
元素,InnerText
和 InnerHtml
属性中包含一些希腊文本。
页面编码为希腊语(Windows)。
我的 if
语句是:
if (mySpan != null && mySpan.InnerText.Contains(greekText))
这行代码 100% 有效,但我之前的无效代码是:
if (mySpan != null && browser.DocumentText.Contains(greekText))
这条线不起作用,当我使用调试器单击预览时,我注意到希腊文本不可读(奇怪的符号而不是希腊字符)。但是,应用程序已成功读取包含希腊文本的所有其他元素,也就是说,我可以将它们的属性保存在变量中并使用它们。有没有解释为什么 DocumentText
失败而 InnerText
成功?
最佳答案
查看WebBrowser.DocumentText
的源代码,它似乎默认使用UTF8编码:
public string DocumentText
{
get
{
Stream documentStream = this.DocumentStream;
if (documentStream == null)
return "";
StreamReader streamReader = new StreamReader(documentStream);
documentStream.Position = 0L;
return streamReader.ReadToEnd();
}
也就是说,使用 StreamReader
而不指定编码将假定 UTF8 编码。
参见this link解决这个问题
我只能假设使用 browser.Document.GetElementById(mySpanId)
尊重页面的规定编码,这就是为什么您在使用此调用时可以正确看到它。
关于c# - Web浏览器文档文本编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10310986/