你是否在打开网站的时候想下载看到所有图片那?
今天那咱们就用cefsharp 来是实现它:
直接上关键代码:
public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
{
var url = new Uri(request.Url);
var extension = url.ToString().ToLower();
if (request.ResourceType == ResourceType.Image || extension.EndsWith(".jpg") || extension.EndsWith(".png") || extension.EndsWith(".gif") || extension.EndsWith(".jpeg"))
{
string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff-") + ".png";
string tmpRootDir = System.AppDomain.CurrentDomain.BaseDirectory + _directory;
if (!System.IO.Directory.Exists(tmpRootDir))
{
System.IO.Directory.CreateDirectory(tmpRootDir);
}
fileName = tmpRootDir + fileName;
Fileutils.DownImageFile(request.Url, fileName);
return;
}}
public CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
{
var m = request.Method;
msg?.Invoke(request.Url);
msg?.Invoke(m);
if (request.Method == "POST")
{
using (var postData = https://www.it610.com/article/request.PostData)
{
if (postData != null)
{
var elements = postData.Elements;
var charSet = request.GetCharSet();
foreach (var element in elements)
{
if (element.Type == PostDataElementType.Bytes)
{
var body = element.GetBody(charSet);
msg?.Invoke(body);
}
}
}
}
}
Uri url;
if (Uri.TryCreate(request.Url, UriKind.Absolute, out url) == false)
{
//If we're unable to parse the Uri then cancel the request
// avoid throwing any exceptions here as we're being called by unmanaged code
return CefReturnValue.Cancel;
}
var extension = url.ToString().ToLower();
if (request.ResourceType == ResourceType.Image || extension.EndsWith(".jpg") || extension.EndsWith(".png") || extension.EndsWith(".gif") || extension.EndsWith(".jpeg"))
{
Console.WriteLine(request.Url);
}return CefReturnValue.Continue;
}
【Cefsharp|使用CEfSharp之旅(12)下载网页所有图片,下载图片】
如图所示所有的图片都出来了。嘎嘎 一个图标都不放过
文章图片
文章图片