这是我的第一篇文章,因为我很绝望。我已经到处搜索了几乎所有内容并尝试了所有内容,但是我无法使其正常运行。既然这个社区已经帮助了我很多,我有一种感觉,这是最好的地方。我需要做的是解析一个使用JavaScript的网站。
关于我的一句话:我所知道的几乎所有东西,我都是自学的。我对基础知识非常有信心,并乐于学习新事物。但是在这一点上,我认为我太愚蠢了,无法理解。
我正在使用WebBrowser类,但是在唯一的控制台应用程序中。我已经读过,您应该避免这种情况,但是我不知道替代方案是什么。因此,我让脚本结束,将网站加载到HtmlAgilityPack.HtmlDocument中,然后解析该文档。
到目前为止,这或多或少起作用(有时无法加载。我认为这是来自同一问题),但仅适用于一个或最多两个网站。如果我尝试加载其他网站,则将无法正常工作,我也不知道为什么。看起来,它必须与线程相关联,但是我对此主题的知识绝对为零,而我对此几乎一无所知。
我希望有人会尝试帮助我,所以(我认为)相关事件代码段:
[STAThread]
static void Main()
{
HtmlNode table = null;
HtmlAgilityPack.HtmlDocument htmlDoc;
htmlDoc = LoadHtmlWithBrowser(url);
table = htmlDoc.DocumentNode.SelectSingleNode(@"//*[@id=""table""]");
}
private static HtmlAgilityPack.HtmlDocument LoadHtmlWithBrowser(String url)
{
System.Windows.Forms.WebBrowser webBrowser1 = new System.Windows.Forms.WebBrowser();
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.AllowNavigation = true;
webBrowser1.Navigate(url);
waitTillLoad(webBrowser1);
while (true)
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
var documentAsIHtmlDocument3 = (mshtml.IHTMLDocument3)webBrowser1.Document.DomDocument;
StringReader sr = new StringReader(documentAsIHtmlDocument3.documentElement.outerHTML);
doc.Load(sr);
webBrowser1.Dispose();
}
}
private static void waitTillLoad(WebBrowser webBrControl)
{
System.Windows.Forms.WebBrowserReadyState loadStatus;
int waittime = 100000;
int counter = 0;
while (true)
{
loadStatus = webBrControl.ReadyState;
Application.DoEvents();
if ((counter > waittime) || (loadStatus == WebBrowserReadyState.Uninitialized) || (loadStatus == WebBrowserReadyState.Loading) || (loadStatus == WebBrowserReadyState.Interactive))
{
break;
}
counter++;
}
counter = 0;
while (true)
{
loadStatus = webBrControl.ReadyState;
Application.DoEvents();
if (loadStatus == WebBrowserReadyState.Complete && webBrControl.IsBusy != true)
{
break;
}
counter++;
}
}