我正在尝试保存网页,以便可以离线查看。我设法从网页中获取 html,但我不知道如何获取所有图像。
这是我用来获取 html 的代码:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(txtUrl.Text);
HttpWebResponse responce = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(responce.GetResponseStream());
string responsehtml = sr.ReadToEnd();
sr.Close();
string path = @"C:\Users\Cargoguide\Pictures\test\test.htm";
File.WriteAllText(path, responsehtml);
Process.Start(path);
最佳答案
您可以让 winform 的 WebBrowser 控件来完成繁重的工作。解析网页后,您可以浏览图像元素以保存每个图像。
private void GetWebpage(string url)
{
WebBrowser browser = new WebBrowser();
browser.Navigate(url);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
}
void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var browser = (WebBrowser)sender;
var client = new WebClient();
foreach (var img in browser.Document.Images)
{
var image = img as HtmlElement;
var src = image.GetAttribute("src").TrimEnd('/');
if (!Uri.IsWellFormedUriString(src, UriKind.Absolute))
{
src = string.Concat(browser.Document.Url.AbsoluteUri, "/", src);
}
//Append any path to filename as needed
var filename = new string(src.Skip(src.LastIndexOf('/')+1).ToArray());
File.WriteAllBytes(filename, client.DownloadData(src));
}
}
关于c# - 使用c#从网页下载所有图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27289454/