背景:
我有一个html页面,其中有几个已存在于文档DOM中的DIV和表。当调用此页面的URL时,JavaScript代码将填充并填充此页面的内容。这可能会花费2~3秒,但最终会很好地完成。
问题: 我想在C#中调用此页面的URL,以便在一个漂亮的html字符串中获取它的内容。
我尝试了很多从SO中学到的技巧。但是,它们都只返回页面的裸骨结构而没有任何内容。其中包括:
现在我的问题是,在调用网址时是否有一种等待加载所有内容的好方法?
对我来说似乎有些选择:
有没有办法告诉其中一个类在下载内容之前等待一段时间?,或者:
WebBrowser类上是否有另一个可以挂钩的事件,以便等待加载所有内容?
提前致谢。
编辑3:
尝试this other solution using HttpWebRequests,但收到此错误: ' HttpWebRequest.HttpWebRequest()'已过时:'此API支持.NET Framework基础结构,不能直接在您的代码中使用。'
编辑2: 即使this other WebBrowser solution也不起作用!!
它引发了JS错误"对象不支持" CallServerSideCode"
编辑1:正如Austin所问,我包含了一些我尝试过的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
WebBrowser wb = new WebBrowser();
public Form1()
{
InitializeComponent();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
}
private void button1_Click(object sender, EventArgs e)
{
using(var webc = new WebClient())
{
var json = webc.DownloadString(textBox1.Text);
Debug.WriteLine("WebClient: \r\n" + json.ToString() + " \r\n\r\n\r\n");
}
}
private void button2_Click(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create(textBox1.Text);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
Thread.Sleep(5000);
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine("Web Request: \r\n" + responseFromServer + " \r\n\r\n\r\n");
// Clean up the streams and the response.
reader.Close();
response.Close();
}
private void button3_Click(object sender, EventArgs e)
{
wb.Navigate(new Uri(textBox1.Text));
}
private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string page = wb.DocumentText;
Console.WriteLine("Web Browser: \r\n" + page + " \r\n\r\n\r\n");
}
}