Capture Bing daily images as the background of the website homepage.

Source: Internet
Author: User

Capture Bing daily images as the background of the website homepage.

Set the Bing search background image as the background of your website to update the background and information daily.

As follows:

Let's take a look at our ideas. First, we need to capture Bing's daily images and the latest information, save the images and information to the local device, and display the pictures and information to the homepage of the website.

Step 1: capture images

First open Bing, then use the developer tool F12, click to review web page elements, and analyze the HTML structure, as shown in:

Here we can see the image address of the background, which is ready to get the image link from the HTML element. So I also downloaded a Jumony help class for extracting Web page elements to obtain the elements of the background-image (Jumony can be searched directly in NuGet management for Jumony, and then installed, finally remember to reference the namespace, Jumony detailed use please move to the http://www.cnblogs.com/Ivony/p/3447536.html)

  

The result shows that the obtained HTML tag does not have the CSS attribute, so the URL of the background image cannot be obtained. What should I do?

Continue to use the developer tool to view the Bing web page. An Ajax request is found and a Json data is returned, for example:

  

This indicates that the Json returned by this request is Bing's daily image information, so that the request URL of the image information can be obtained. view the message header:

  

Request URL: http://cn.bing.com/HPImageArchive.aspx? Format = js & idx = 0 & n = 1 & nc = 1470798060031 & pid = hp & video = 1

Then check the parameters that can be omitted in the request, and finally get the URL: http://cn.bing.com/HPImageArchive.aspx? Format = js & idx = 0 & n = 1

Next we need to obtain Json data in the program and use WebClient for webpage requests:

  

In this case, we need to parse the Json to obtain the desired data, that is, the URL of the background image:

There are many ways to parse Json: Json is converted to able, Json deserialization, and third-party components,

Here we use a method we are good at: VS's built-in javaScriptSerializer class converts wallejson into a model. This model is created based on the returned Json data structure.

After resolution, the image URL is obtained. Save the image to the local device according to the DownLoadFile () method of WebClient;

Attached model:

1 // parse Json data returned by Bing 2 3 4 public class Walle 5 {6 public List <images> images {get; set;} 7 public tooltips {get; set ;} 8} 9 10 public class images11 {12 public string startdate {get; set;} 13 public string fullstartdate {get; set;} 14 public string enddate {get; set ;} 15 public string url {get; set;} 16 public string urlbase {get; set;} 17 public string copyright {get; set;} 18 public string copyrightlink {get; set ;} 19 public string wp {get; set;} 20 public string hsh {get; set;} 21 public string drk {get; set;} 22 public string top {get; set ;} 23 public string bot {get; set;} 24 public List <int> hs {get; set;} 25 26 27} 28 29 public class tooltips30 {31 public string loading {get; set;} 32 public string previous {get; set;} 33 public string next {get; set;} 34 public string walle {get; set;} 35 public string Wils {get; set;} 36 37}

 

 

Step 2: obtain daily information

We want to obtain the data here:

 

Continue to use the developer tool to view the data location:

  

So you can use Jumony to capture data,

The result is very depressing. The HTML page cannot find the element content of the class "maid.

After carefully checking the network connection, I found a very interesting thing:

For example:

After opening this request:

  

It turned out to be a separate page. No wonder I couldn't find it on the original page. Now let's do it:

Request to save this page: http://cn.bing.com/cnhp/life? CurrentDate = 20160809 & IID = SERP.5045 & IG = CC0CACB23C324D99A37ACF3604BF19FE,

After a simple test, currentDate is the date of the current day, and other parameters are not required.

The following code is used to capture data based on Jumony:

  

String date = DateTime. Now. ToString ("yyyyMMdd"); // get text information string BingUrl = "https://cn.bing.com/cnhp/life? CurrentDate = "+ date; var Source = new JumonyParser (). loadDocument (BingUrl); string Title = ""; string Text = ""; // Title foreach (var item in Source. find (". maid>. hplatt ") {Title = item. innerText ();} // text foreach (var item in Source. find ("# maid") {Text = item. innerText ();}

 

 

Step 3: Save the data locally

The pictures and information have been obtained in the previous two steps, and the data should be saved,

In general, we store image paths and information data to the database, but the requirement is to replace the background of the original homepage of the website, which is biased towards improving the UI. It is not appropriate to change the database.

In addition, images are updated daily, and the system automatically obtains the data. The data is only provided for daily queries, and the write operation is performed once a day.

Solution: The image uses the current date as the file name, and the information is in XML format. The file name is also the current date (such as 20160810) and saved to the website directory, each time the homepage is loaded, the system checks whether the Xml file or JPG file with the current date as the file name exists. If the file does not exist, the program captures Bing images and daily information. If the file exists, the obtained data is transmitted to the homepage for display.

Save the information as XML. Here I use XmlSerializer to convert the Model and create an XML file. This Model is mainly created based on the saved information. The fields include the title, subtitle, and text information, image path, current date. Deserializing XML to Model when getting data;

Model:

    

1 // <summary> 2 // used to save and transmit Bing background images and text information 3 /// </summary> 4 public class BgImages 5 {6 // <summary> 7 // Title 8 /// </summary> 9 public string Title {get; set;} 10 11 /// <summary> 12 // subtitle 13 /// </summary> 14 public string STitle {get; set ;} 15 /// <summary> 16 // Text 17 /// </summary> 18 public string Text {get; set ;} 19 /// <summary> 20 /// image path 21 /// </summary> 22 public string Url {get; set ;} 23 /// <summary> 24 /// save Date 25 /// </summary> 26 public string Date {get; set;} 27}View Code

 

    

Complete code in the controller is attached:

1 # region online image capturing 2 3 /// <summary> 4 // read background information 5 /// </summary> 6 /// <returns> </returns> 7 public ActionResult ReturnBgInfo () 8 {9 // read the XML file 10 string Path = Server. mapPath ("/Images/BingInfo/" + DateTime. now. toString ("yyyyMMdd") + ". xml "); 11 12 FileInfo file = new FileInfo (Path); 13 14 if (! File. exists) 15 {16 GetNewBing (); 17} 18 19 FileStream files = new FileStream (Path, FileMode. open); 20 XmlSerializer xml = new XmlSerializer (typeof (BgImages); 21 BgImages BgImage = (BgImages) xml. deserialize (files); 22 files. close (); 23 24 return Json (BgImage ); 25 26} 27 28 /// <summary> 29 //// networked capture image 30 /// </summary> 31 public void GetNewBing () 32 {33 string date = DateTime. now. toString ("yyyyMMdd"); 34 35 36 // obtain text information 37 string BingUrl =" https://cn.bing.com/cnhp/life?currentDate= "+ Date; 38 39 var Source = new JumonyParser (). loadDocument (BingUrl); 40 string Title = ""; 41 string Text = ""; 42 string STitle = ""; 43 44 // Title 45 foreach (var item in Source. find (". maid>. hplatt ") 46 {47 Title = item. innerText (); 48} 49 50 // subtitle 51 foreach (var item in Source. find (". maid>. maid ") 52 {53 STitle = item. innerText (); 54} 55 56 // text 57 foreach (var item in Source. find ("# maid") 58 {59 Text = item. innerText (); 60} 61 62 63 // Bing url 64 string url =" http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1 "; 65 66 // obtain Bing's image Json data 67 WebClient BingClient = new WebClient (); 68 BingClient. encoding = System. text. encoding. UTF8; // define the encoding language of the object, here or gb2312 69 string wallejson = BingClient. downloadString (url); 70 71 if (wallejson! = "Null") 72 {73 // parse Json data 74 using criptserializer = new using criptserializer (); 75 Walle walleinfo = Using criptserializer. deserialize <Walle> (wallejson); 76 77 // Save the image to a local 78 string ImagePath = DateTime. now. toString ("yyyyMMdd") + ". JPG "; 79 BingClient. downloadFile (walleinfo. images. first (). url, Server. mapPath ("/Images/BingInfo/") + ImagePath); 80 81 // Save the information to Model -- BgImages 82 BgImages model = new BgImages (); 83 model. date = walleinfo. images. first (). enddate; 84 model. text = Text; 85 model. title = Title; 86 model. STitle = STitle; 87 model. url = "/Images/BingInfo/" + ImagePath; 88 89 string xmlPath = Server. mapPath ("/Images/BingInfo/" + DateTime. now. toString ("yyyyMMdd") + ". xml "); 90 91 // serialize XML 92 CreateXML (model, xmlPath ); 93 94} 95 96} 97 98 99 100 101 # region XML serialization 102 public void CreateXML (BgImages model, string Path) 103 {104 FileStream fs = new FileStream (Path, FileMode. create); 105 // execute XML serialization 106 XmlSerializer xml = new XmlSerializer (typeof (BgImages); 107 xml. serialize (fs, model); 108 fs. close (); 109} 110 # endregion111 # endregionView Code

 

    

Step 4: display data on the home page

Because the background image on the left of the homepage is a master page, the image display is mainly implemented through js.

When loading a page, use Ajax requests to obtain data in the background,

The Code is as follows:

$ (Document ). ready (function () {// loads the background image and text information $. post ("/Test/ReturnBgInfo", function (data) {$ ("# animate-area" ).css ("background-image", "url (" + data. url + ")"); $ ("# Title" ).html (data. title); $ ("# STitle" comment .html (data. STitle); $ ("# Text" ).html (data. text );});})

  

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.