I will leave an answer that meets your need, but using another approach. If your need is to read HTML content from a page on the web, you will find it very difficult to do this using Webbroser control, especially outside of a Windows Forms application. I managed to accomplish what you need using the class System.Net.WebClient
and the library HTML Agility Pack. Just change the variable value nomeDoCanal
to the channel you want to read the data:
HtmlDocument doc = new HtmlDocument();
WebClient client = new WebClient();
string nomeDoCanal = "FOO";
string source = client.DownloadString(String.Format("https://www.youtube.com/user/{0}/about", nomeDoCanal));
doc.LoadHtml(source);
HtmlNode node = doc.DocumentNode.Descendants("ul").FirstOrDefault(d => d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("about-stats"));
HtmlNode[] itens = node.Descendants("li").ToArray();
HtmlNode liSubscribers = itens[0];
HtmlNode liViews = itens[1];
string subscribers = liSubscribers.Element("b").InnerText;
string views = liViews.Element("b").InnerText;
Console.WriteLine("Subscribers: {0}", subscribers);
Console.WriteLine("Views: {0}", views);
Console.ReadKey();
To get the HTML Agility Pack library using nuget:
PM> install-package htmlagilitypack
If you cannot use Nuget, you can download a version here (link Release Binaries):
https://www.nuget.org/api/v2/package/HtmlAgilityPack/1.5.5
Exchange 1.5.5 for the desired version on the nuget page itself https://www.nuget.org/packages/HtmlAgilityPack/, on the right side, there is a link called "manual download"
The relevant HTML snippet from the Youtube page is as follows. Keep in mind that any changes to Youtube layout will stop this program from working:
<ul class="about-stats">
<li class="about-stat ">
<b>312,992</b> subscribers
</li>
<li class="about-stat ">
<b>71,629,148</b> views
</li>
Link to the library website:
http://html-agility-pack.net/
This question is very confusing... what does it have to do
MTAThread
with making web requests?– Miguel Angelo
It’s like when I make a web request the application hangs and after a long time returns. But that’s what enters Mtathread. If Stathread causes the app to crash when it calls Thread.Sleep it will be that Mtathread disrupts Thread.Sleep also?
– FRNathan13
I think you should reformulate the question, because currently it is difficult to understand where you want to get. Avoid using
MTAThread
, there is no reason to use it in this case, see this question for more details. Another thing, is needed theWebBrowser
? it is not easier to make a request and process the information received?– stderr
MTAThread
andSTAThread
have no connection with theThread.Sleep
, they apply only to the way certain COM objects behave in a Multi-threaded application and probably have nothing to do with your problem.– Leandro Godoy Rosa