【发布时间】:2016-10-15 07:17:55
【问题描述】:
我需要在类库中创建一个方法来获取 URL 的内容(可能由 JavaScript 动态填充)。
我一无所知,但是整天搜索这就是我想出的:(大部分代码来自here)
using System;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
public static class WebScraper
{
[STAThread]
public async static Task<string> LoadDynamicPage(string url, CancellationToken token)
{
using (WebBrowser webBrowser = new WebBrowser())
{
// Navigate and await DocumentCompleted
var tcs = new TaskCompletionSource<bool>();
WebBrowserDocumentCompletedEventHandler onDocumentComplete = (s, arg) => tcs.TrySetResult(true);
using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true))
{
webBrowser.DocumentCompleted += onDocumentComplete;
try
{
webBrowser.Navigate(url);
await tcs.Task; // wait for DocumentCompleted
}
finally
{
webBrowser.DocumentCompleted -= onDocumentComplete;
}
}
// get the root element
var documentElement = webBrowser.Document.GetElementsByTagName("html")[0];
// poll the current HTML for changes asynchronosly
var html = documentElement.OuterHtml;
while (true)
{
// wait asynchronously, this will throw if cancellation requested
await Task.Delay(500, token);
// continue polling if the WebBrowser is still busy
if (webBrowser.IsBusy)
continue;
var htmlNow = documentElement.OuterHtml;
if (html == htmlNow)
break; // no changes detected, end the poll loop
html = htmlNow;
}
// consider the page fully rendered
token.ThrowIfCancellationRequested();
return html;
}
}
}
它当前抛出此错误
ActiveX 控件 '8856f961-340a-11d0-a96b-00c04fd705a2' 不能 实例化,因为当前线程不在单线程中 公寓。
我接近了吗?上面有解决办法吗?
或者如果我偏离了轨道,是否有现成的解决方案可以使用 .NET(可以从类库调用)获取动态 Web 内容?
【问题讨论】:
标签: c# .net web-scraping