之前用了很久网上各种各样的bing壁纸的小程序一个是很卡,操作复杂,主要是用着用着就不能用了,换了软件依然与此,干脆自己写个小程序。
找到bing网站,查看网站首页html代码,了解到获取到css/js端的图片链接地址和标签所在位置。C#中WebClient类可以有效获取网站内容,最后通过正则可以找到图片URL,下载之后保存到指定目录。
public static void catchBINGpic()
{
try
{
WebClient MyWebClient = new WebClient();
MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
Byte[] pageData = MyWebClient.DownloadData("http://global.bing.com/"); //从指定网站下载数据
//string pageHtml = Encoding.Default.GetString(pageData); //如果获取网站页面采用的是GB2312,则使用这句
string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8,则使用这句
//Console.WriteLine(pageHtml);//在控制台输入获取的内容
string content = System.Text.Encoding.UTF8.GetString(pageData);
string regex = "g_img={url.*?jpg";
Regex re = new Regex(regex);
MatchCollection matches = re.Matches(content);
System.Collections.IEnumerator enu = matches.GetEnumerator();
while (enu.MoveNext() && enu.Current != null)
{
Match match = (Match)(enu.Current);
string url1 = match.Value.Substring(match.Value.IndexOf('"') + 1);
string path = "http://cn.bing.com" + url1;
Console.Write(path + "\r\n");
HttpClient httpClient = new HttpClient();
httpClient.MaxResponseContentBufferSize = 10240000;
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");
HttpResponseMessage response = httpClient.GetAsync(new Uri(path)).Result;
byte[] buffs = response.Content.ReadAsByteArrayAsync().Result;
string path_ = Regex.Replace(path.Substring(path.LastIndexOf('/') + 1), @"[\\|/|:|*|?|\""|<|>|\|]", "");
string url = "C:\\Users\\bhnd\\Desktop\\bingpic\\" + path_;
File.WriteAllBytes(url, buffs);
}
Console.WriteLine("结束");
Console.ReadLine(); //让控制台暂停,否则一闪而过了
}
catch (WebException webEx)
{
Console.WriteLine(webEx.Message.ToString());
}
}
如果网站HTML端修改了呈现每日壁纸的代码,需要修改自己的代码来适应。
为了方便每天桌面上都可以用最新的壁纸设置下载文件夹到桌面壁纸。
纯自动程序可以通过C# 的windowsService类构建服务程序,构建程序然后启动生成之后就可以在设置服务自动启动。
需要考虑网络问题,比如开机之后服务程序可能优先于windows的网络连接启动,需要做延时THREAD.SLEEP(1000*60);或者直接方法中开启断线重连。