【问题标题】:How to Search a Text on a WebBrowser?如何在 WebBrowser 上搜索文本?
【发布时间】:2013-03-20 16:04:25
【问题描述】:

我是 C# 的初学者,但我有一个问题。 每次在执行搜索请求后,我需要在 webBrowser 控件中发现一个事件时弹出一个消息框,此时将选择该事件。 我正在使用计时器来刷新 webBrowser 并再次启动搜索。这就像一个通知系统。

using System;
using System.Windows.Forms;
using mshtml;

namespace websearch
{

public partial class Form1 : Form
{
    Timer temp = new Timer();
    //Timer refreshh = new Timer();
    public Form1()
    {        
        InitializeComponent();
        temp.Tick += new EventHandler(refreshh_Tick);
        temp.Interval = 1000 * 5;
        temp.Enabled = true;
        temp.Start();
        WebBrowser1.Navigate("http://stackoverflow.com/");
    }

    void refreshh_Tick(object sender, EventArgs e)
        {
            WebBrowser1.Refresh();
            WebBrowser1.DocumentCompleted += Carder_DocumentCompleted;
        }

    private void Carder_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            FindNext("C#", WebBrowser1);
            temp.Tick += refreshh_Tick;
        }
    public void FindNext(string text, WebBrowser webBrowser2)
        {

            IHTMLDocument2 doc = webBrowser2.Document.DomDocument as IHTMLDocument2;
            IHTMLSelectionObject sel = doc.selection;
            IHTMLTxtRange rng = sel.createRange() as IHTMLTxtRange;

            rng.collapse(false); // collapse the current selection so we start from the end of the previous range
            if (rng.findText(text))
              {
                rng.select();
                MessageBox.Show("Theire are new C# Question");              
              }

        }
    }

}

【问题讨论】:

    标签: c# winforms webbrowser-control


    【解决方案1】:

    有几种方法可以做到这一点:

    1. 创建一个递归函数来解析所有HtmlElements 并检查内容。如果您需要的文本存在,您可以选择元素,或更改元素样式或执行您可能想要执行的任何其他操作。

    例如:

    public bool SearchEle(HtmlElement ele, string text)
    {
        foreach (HtmlElement child in ele.Children)
        {
            if (SearchEle(child, text))
                return true;
        }
        if (!string.IsNullOrEmpty(ele.InnerText) && ele.InnerText.Contains(text))
        {
            ele.ScrollIntoView(true);
            return true;
        }
    
        return false;
    }
    
    1. 您使用webBrowser2.Document.Body.InnerText 并进行字符串搜索。如果您实际上不打算在视觉上突出显示文本,而只是想找到文本。

    另一方面,您可能希望将代码 WebBrowser1.DocumentCompleted += Carder_DocumentCompleted; 移动到 Form1() 构造函数,而不是每次调用刷新函数 refreshh_Tick 时都这样做。

    【讨论】:

    • 假设你搜索<div> find me (the first one) <a href="something">I am the second me</a> the rest.</div>找到me,你的代码找不到第一个我。
    • 只需交换 foreachif 块。
    • 如果第一个if可以在其innerText中找到文本,则无需搜索子元素,因为元素的innerText包含其子元素的innerText
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 2012-06-28
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    相关资源
    最近更新 更多