Get element by ID from webbrowser and show in label

五迷三道 提交于 2019-12-11 04:37:36

问题


So I a having a issue.. I want to show the text from a webpage, on the label on my Windows Application Form. Here is the "Inspect Element" code:

<ul id="userInfoNav">
<li>Rank: <span class="value">Sivilist</span></li>
<li>Bosted: <span class="value">Oslo</span></li>
<li>Gjeng: <span class="value">Ingen</span></li>
<li>Penger: <span id="money_hand" class="value">16,000 kr</span></li>
<li>Kuler: <span class="value">0 stk</span></li>

I have tried using:

web.Document.GetElementById("userInfoNav").InvokeMember("Value", label1.Text);

But it doesn't do anything..

The texts can change from time to time also..


回答1:


To get the outer text:

statsTextBox.Text = web.Document.GetElementById("userInfoNav").OuterText;

And to check if the ID exist, before executing the code:

HtmlElement htmlelement = web.Document.GetElementById("userInfoNav");
            if (htmlelement == null)
            {
                return;
            }
            else
            {
                statsTextBox.Text = web.Document.GetElementById("userInfoNav").OuterText;
            }



回答2:


The question is not nearly well expressed, but taken from the comments, there are several things that may be what you want:

  1. The complete inner html in <ul id="userInfoNav"> (notice that since ul is an unclosed tag, the contents might be different than what you are expecting):

    label1.Text = webBrowser1.Document.GetElementById("userInfoNav").innerHtml;
    
  2. The html on each <li>:

    var elem = webBrowser1.Document.GetElementById("userInfoNav");
    foreach (var child in elem.Children.OfType<HtmlElement>())
    {
      label1.Text += child.InnerHtml;  // child.InnerHtml contains the html of    each li
      // You can use child.InnerText which would remove the html tags (<span>)
    }
    
  3. What you said was what you wanted in the comments (i.e., "Rank" "Bosted" "Gjeng" "Penger and "Kuler"). Code specific for this very case and not general:

    var elem = webBrowser1.Document.GetElementById("userInfoNav");
    foreach (var child in elem.Children.OfType<HtmlElement>())
    {
      label1.Text += child.InnerText.Split(':')[0]);  
    }
    

I presume neither of these three is what you want, but this is as much as I can do without you specifying more. At the very least, it should give you an idea of how to access the data



来源:https://stackoverflow.com/questions/28344280/get-element-by-id-from-webbrowser-and-show-in-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!