首页 / HTML / 如何通过c#获取html页面源代码
如何通过c#获取html页面源代码
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何通过c#获取html页面源代码,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1898字,纯文字阅读大概需要3分钟。
内容图文
![如何通过c#获取html页面源代码](/upload/InfoBanner/zyjiaocheng/820/e1980107eae941cd910b2ea0b7b4ed7c.jpg)
我希望从url或url以.htm在本地驱动器中保存完整的网页asp但我没有成功.
码
public StreamReader Fn_DownloadWebPageComplete(string link_Pagesource)
{
//--------- Download Complete ------------------
// using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
// {
//client
//HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(link_Pagesource);
//webRequest.AllowAutoRedirect = true;
//var client1 = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(link_Pagesource);
//client1.CookieContainer = new System.Net.CookieContainer();
// client.DownloadFile(link_Pagesource, @"D:\S1.htm");
// }
//--------- Download Page Source ------------------
HttpWebRequest URL_pageSource = (HttpWebRequest)WebRequest.Create("https://www.digikala.com");
URL_pageSource.Timeout = 360000;
//URL_pageSource.Timeout = 1000000;
URL_pageSource.ReadWriteTimeout = 360000;
// URL_pageSource.ReadWriteTimeout = 1000000;
URL_pageSource.AllowAutoRedirect = true;
URL_pageSource.MaximumAutomaticRedirections = 300;
using (WebResponse MyResponse_PageSource = URL_pageSource.GetResponse())
{
str_PageSource = new StreamReader(MyResponse_PageSource.GetResponseStream(), System.Text.Encoding.UTF8);
pagesource1 = str_PageSource.ReadToEnd();
success = true;
}
错误:
Too many automatic redirections were attempted.
尝试使用此代码但未成功.
许多网址使用此代码成功,但此网址不成功.
解决方法:
这是方法
string url = "https://www.digikala.com/";
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
}
}
}
结果变量将包含HTML页面,然后您可以将其保存为这样的文件
System.IO.File.WriteAllText("path/filename.html", result);
注意您必须使用命名空间
using System.Net.Http;
如果您使用的是旧版VS,那么您可以看到此answer用于同一目的使用WebClient和WebRequest,但实际上更新VS是一个更好的解决方案.
内容总结
以上是互联网集市为您收集整理的如何通过c#获取html页面源代码全部内容,希望文章能够帮你解决如何通过c#获取html页面源代码所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。