玉祥平台客服-15087858732

标题: 使用C#正则表达式获取必应每日图片地址 [打印本页]

作者: Adam丶鱼    时间: 2020-3-24 17:54
标题: 使用C#正则表达式获取必应每日图片地址
微软的Bing搜索引擎首页每天都会提供了一些有趣的图片,下面使用正则表达式获取图片的地址,不管是在手机app还是在网站上都是很好的图片素材,而且每天更新,非常不错。
    首先访问微软的API,该地址返回的是xml文本,获取xml文本后使用正则表达式匹配url节点中的内容,加上必应主页链接即可获得图片的真实网址。下面是获取网址的全部代码。
string InfoUrl = "http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InfoUrl);
request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8";
string XmlString;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
   Stream myResponseStream = response.GetResponseStream();
   using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8))
   {
       XmlString = myStreamReader.ReadToEnd();
   }
}
// 定义正则表达式用来匹配标签
Regex regImg = new Regex("<Url>(?<imgUrl>.*?)</Url>", RegexOptions.IgnoreCase);
// 搜索匹配的字符串
MatchCollection matches = regImg.Matches(XmlString);
// 取得匹配项列表
string ImageUrl = "http://www.bing.com" + matches[0].Groups["imgUrl"].Value;
background_image.Src = ImageUrl;


作者: 张兴康    时间: 2020-3-24 18:05

作者: Adam丶鱼    时间: 2020-3-24 18:07
张兴康 发表于 2017-4-24 18:05


作者: 张兴康    时间: 2020-3-25 17:40

作者: Adam丶鱼    时间: 2020-3-25 21:56
张兴康 发表于 2017-4-25 17:40


作者: 张兴康    时间: 2020-3-26 20:08





欢迎光临 玉祥平台客服-15087858732 (http://bbs.delit.cn/) Powered by Discuz! X3.2