如何使用C#下载动态网页源?更具体地说,例如,我有一个页面http://example.com。下载源代码,但由于AJAX,它在源代码中添加了几行代码,收集后,我得不到我想要的东西。有谁知道如何“刷新”源,或者如果有的话有办法实现这样的东西?您现有的“静态”代码:
WebClient client = new WebClient();
Byte[] pageData = client.DownloadData("http://example.com" + address);
string pageHtml = Encoding.UTF8.GetString(pageData);
Console.WriteLine(pageHtml);
Console.ReadKey();
问候。
答案 0 :(得分:2)
您可以使用WebBrowser组件创建表单。我们假设您将其命名为browser
private void PrepareDocument()
{
browser.Navigate("http://somewebsite.com");
var timer = new Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
}
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
//parse the document, find the data that should be loaded after ajax call
if(browser.ReadyState == WebBrowserReadyState.Complete &&
browser.Document.GetElementById("ajax-divId") != null)
{
timer.Enabled=false;
ProceedOnDocument();
}
}
private void ProceedOnDocument()
{
//your code here
}