代码之家  ›  专栏  ›  技术社区  ›  user

C#-在WebBrowser中修剪HTML片段

  •  0
  • user  · 技术社区  · 16 年前

    下面是一个例子:

    <div class="alertText">26 friends joined</div>
    

    修剪:

    26

    很抱歉描述得很模糊,但我真的不知道该怎么说。非常感谢。

    3 回复  |  直到 16 年前
        1
  •  1
  •   T. Stone    16 年前

    html = WebBrowser1.Document.documentElement.OuterHTML
    pattern = @'<div class="alertText">(\d{1,2}) friends joined</div>'
    for Match m in Regex.Matches(html, pattern) {
        friendsJoined = Convert.ToInt32(m.Groups[1].Value)
    }
    

    如果您希望抓取更少地依赖于HTML,您可以删除outerbits。。。

    html = WebBrowser1.Document.documentElement.OuterHTML
    pattern = @'>(\d{1,2}) friends joined</'
    for Match m in Regex.Matches(html, pattern) {
        friendsJoined = Convert.ToInt32(m.Groups[1].Value)
    }
    
        2
  •  0
  •   Casper Broeren    16 年前

    我想说,这是一个更好的正则表达式匹配;

    html = WebBrowser1.Document.documentElement.OuterHTML
    pattern = @'(\d+)\sfriends\sjoined'
    for Match m in Regex.Matches(html, pattern) {
        friendsJoined = Convert.ToInt32(m.Groups[1].Value)
    }
    
        3
  •  0
  •   Majkel    16 年前

    你的意思是这样的:

    string numberOfFriends;
    
    HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName( "div" );
    foreach( HtmlElement elem in elems )
    {
      string className = elem.GetAttribute( "className" );
      if( !string.IsNullOrEmpty( className ) && "alertText".Equals( className ) )
      {
        string content = elem.InnerText;
        if( Regex.IsMatch( content, "\\d+ friends joined" ) )
        {
          numberOfFriends = Regex.Match( content, "(\\d+) friends joined" ).Groups[ 1 ].Value;
        }
      }
    }
    

    我不完全确定正则表达式是否完全正确,但其余的都应该有效。

    改变 Groups[ 0 ] Groups[ 1 ] -IIRC第一组是整场比赛。

    编辑2: 改变 elem.GetAttribute( "class" ) elem.GetAttribute( "className" ) -固定属性名和固定变量名( class className ).