【问题标题】:I wish to replace text in a web page in C#我希望用 C# 替换网页中的文本
【发布时间】:2020-04-02 00:35:45
【问题描述】:

这是我正在使用的代码

 private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
     IHTMLDocument2 doc2 = webBrowser1.Document.DomDocument as IHTMLDocument2;
     StringBuilder html = new StringBuilder(doc2.body.outerHTML);

     String substitution = "<span style='background-color: rgb(255, 255, 0);'> sensor </span>";
     html.Replace("sensor", substitution);

     doc2.body.innerHTML = html.ToString();

       }

它可以工作,但我无法使用表单网络浏览器

我已经尝试添加

webBrowser1.Document.Write(html.ToString()); //在doc2之后

但显示的网页格式不正确

我将不胜感激,以解决此问题修复

【问题讨论】:

  • 我怀疑 webBrowser1_DocumentCompleted 出现得太晚,无法正常工作。
  • 感谢您的回复.. 我可以解决这个问题吗.. 减慢 webBrowser_DocumentCompleted
  • 事件不是这样运作的。我认为你需要重新评估你的方法。

标签: c# text replace mshtml


【解决方案1】:

您首先需要在 HTMLDocument DOM 中找到您的元素,然后使用相关的 HTML 操作 innerHTML 属性。

有多种方法可以做到这一点,包括注入 javascript (here) 或使用 HtmlAgilityPack

以下代码使用GetElementsByTagName DOM 函数遍历本站文档中的span 标签:https://www.w3schools.com/html/

它将所有跨度文本(包括“教程”)替换为您提供的 html sn-p。

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    var elements = webBrowser1.Document.GetElementsByTagName("span");
    foreach (HtmlElement element in elements)
    {
        if(string.IsNullOrEmpty(element.InnerText)) 
            continue;

        if (element.InnerText.Contains("Tutorial"))
        {
            element.InnerHtml = "<span style='background-color: rgb(255, 255, 0);'> sensor </span>";
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-15
    • 2021-11-18
    • 1970-01-01
    • 2021-01-18
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多