问题
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:
The complete inner html in
<ul id="userInfoNav">
(notice that sinceul
is an unclosed tag, the contents might be different than what you are expecting):label1.Text = webBrowser1.Document.GetElementById("userInfoNav").innerHtml;
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>) }
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