在HTML元素的文本中搜索

时间:2015-11-18 17:47:11

标签: javascript c# .net winforms webbrowser-control

我想使用C#(winforms)中的webBrowser控件API或使用注入的java脚本在特定网页元素中搜索单词。

我使用了以下java脚本并将其注入加载的网页:

var TRange=null;

function findString (str) {

 var strFound;

  // EXPLORER-SPECIFIC CODE

  if (TRange!=null) {
   TRange.collapse(false);
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
  else if (TRange==null || strFound==0) {
   TRange=self.document.body.createTextRange();
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }

 if (!strFound) alert ("String '"+str+"' not found!")
 return;
}

此代码适用于整个页面,但我想在特定元素的内部文本中进行搜索。如何限制搜索到这样的元素?

3 个答案:

答案 0 :(得分:1)

您需要:

  1. 添加对Microsoft.mshtml.dll
  2. 的引用
  3. 然后使用webBrowser1.Document.Body.DomElement
  4. 从正文中获取IHTMLBodyElement
  5. 然后找到您的代码并从代码中获取IHTMLElement
  6. 然后使用IHtmlTextRange
  7. 从正文中获取createTextRange
  8. 然后使用moveToElementText
  9. 将搜索范围限制为您的代码
  10. 然后使用findText
  11. 查找范围中的字符串
  12. 然后,如果找到了字符串,您可以select
  13. 实施例

    以下是我们在"some"中找到"div2"文字的工作示例,而我们有2个div元素,div1div2,并且这两个元素都包含"some"文字。

    <强>表格

    创建Form并在WebBrowser上放置Form1控件并编写此代码:

    public Form1()
    {
        InitializeComponent();
        this.Load += Form1_Load;
        this.webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
    }
    
    private void Form1_Load(object sender, EventArgs e)
    {
        this.webBrowser1.Navigate(@"D:\file.html");
    }
    
    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        var searchText="some";
        var body = webBrowser1.Document.Body.DomElement as IHTMLBodyElement;
        var tag= webBrowser1.Document.GetElementById("div2").DomElement as IHTMLElement;
    
        var range = body.createTextRange();
        range.moveToElementText(tag);
        if (range.findText(searchText, searchText.Length, 0))
            range.select();
        else
            MessageBox.Show(string.Format("String '{0}' not found.", searchText));
    }
    

    示例Html内容

    以下是file.html的测试内容:

    <html>
    <head><title>Select content</title></head>
    <body>
        <div id="div1">Here is some content</div>
        <div id="div2">Here is some other content</div>
    </body>
    </html>
    

    <强>截图

    以下是截图:

    enter image description here

    注意

    • 您可能需要在代码中添加一些空检查。
    • 您可以使用其他属性找到该元素,例如使用name属性:
    • 对于javascript解决方案,您可以查看Ahmad answer here
    var tag = this.webBrowser1.Document.Body.All.GetElementsByName("somename")
                  .Cast<HtmlElement>()
                  .FirstOrDefault().DomElement as IHTMLElement;
    

答案 1 :(得分:1)

以下在第一次调用中使用moveToElementText的java脚本(当TRange为空时)可以使用

var TRange=null;

function findString (str) {

 var strFound;

  // EXPLORER-SPECIFIC CODE

  if (TRange!=null) {
   TRange.collapse(false);
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
  else if (TRange==null || strFound==0) {
   TRange=self.document.body.createTextRange();
   var elem = document.getElementById('my_elem');
   // go to the element text
   TRange.moveToElementText(elem);
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }

 if (!strFound) alert ("String '"+str+"' not found!")
 return;
}

答案 2 :(得分:0)

我假设您知道如何获取元素的DOM引用。接下来,您可以使用JQuery过滤元素中的文本节点,如:

  $($element.contents()).filter(function(){
    return this.nodeType === 3; // filter textnodes only

  }).each(function(){

    findString(this.textContent);
  });