Use C regular expressions to get Bing daily picture addresses

  • 2021-12-12 09:32:57
  • OfStack

Microsoft's Bing search engine homepage will provide a few interesting pictures every day. The following uses regular expressions to get the address of the pictures, which is a good picture material whether on the mobile phone app or on the website, and it is updated every day, which is very good.

First visit Microsoft's API, which returns xml text. After obtaining xml text, match the contents in url node with regular expression, and add Bing homepage link to get the real URL of the picture. The following is the full code to get the 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();
  }
}
//  Define regular expressions to match labels 
Regex regImg = new Regex("<Url>(?<imgUrl>.*?)</Url>", RegexOptions.IgnoreCase);
//  Search for matching strings 
MatchCollection matches = regImg.Matches(XmlString);
//  Get a list of matches 
string ImageUrl = "http://www.bing.com" + matches[0].Groups["imgUrl"].Value;
background_image.Src = ImageUrl;

Related articles: