我想创建webbrowser(在.Net Webbrowser控件的帮助下),可以控制其请求。 例如, 我可以设法通过删除img src来防止图像加载。 但我无法找到某种方法来限制web浏览器对css文件,js文件和CSS文件中使用的图像文件请求的webbrowser控制请求。 这种限制是有条件的。对于某些网站,我希望一切都很自然,但对于某些网站来说,它应该是可配置的。
原因:希望向服务器发送较少的请求,增加响应时间并减少流量。
我使用下面的代码来防止加载图片。同样的方式我想要一些逻辑,它会阻止向css或我可以决定的任何其他文件发送请求。
private void webBrowser1_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e) { if (webBrowser1.Document != null) { foreach (HtmlElement imgElemt in webBrowser1.Document.Images) { if (imgElemt.Id == "divImagePath") { continue; } imgElemt.SetAttribute("src", ""); } } }
答案 0 :(得分:-1)
最好使用System.Net.Http.HttpClient
class来请求页面。这样你就可以获得网页了。您可以从网站上解析您想要的内容,并以相同的方式请求这些项目。
HttpClient client = new HttpClient();
try
{
// Make an asynchronous call to get the web page
HttpResponseMessage response = await client.GetAsync("http://www.msn.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Do something more useful with the returned page
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
// Need to call dispose on the HttpClient object when we
// are done using it, so the app doesn't leak resources
client.Dispose(true);
如果需要显示已拉出的内容,可以在表单上的WebBrowser控件中显示它。但这会拉出与页面相关的所有内容。