201702211618取得各單位網頁數量 - 以 C# 取得 Google site: 搜尋
通常我們想知道網站資料能被 Google 搜尋引擎找到多少筆,我們會在搜尋列中輸入「site:url」,上圖就是以 site:nthu.edu.tw 為例,可以得知清華大學的網頁數量約有 171萬筆。但是......如果每個月想知道交通大學內各單位的網頁數量增減,隨便來個50個單位要知道筆數就會煩死人,那麼讓我們簡單用個 C# 主控台程式來幫助我們取得資料。
所需元素:
1. VS.NET 我是用 2013 版,但什麼版本都沒差。
2. 使用額外的函示庫「HtmlAgilityPack」
3. Google 使用「site:url 」所取得的網頁數量是包在 div resultStats 區塊裡,所以底下處理的 pattern 會以此做關鍵字。
步驟:
Step 1. 下載 HtmlAgilityPack 並解壓縮
Step 2. 新增專案並將「HtmlAgilityPack」加入參考
Step 3. 撰寫程式碼
--------------------------------------------------------------------
Step 1. 下載 HtmlAgilityPack 並解壓縮
連結到「https://htmlagilitypack.codeplex.com/ 」然後下載 https://htmlagilitypack.codeplex.com/downloads/get/437941#
我是使用 Net45 (.net Framework 4.5)
Step 2. 新增專案並將「HtmlAgilityPack」加入參考
在下方圖片操作加入參考,選擇上圖解壓縮後的 Net45 路徑檔案
Step 3. 撰寫程式碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack; //新增
using System.Xml; //新增
namespace Google_search
{
class Program
{
static void Main(string[] args)
{
string[] weblist = new string[] { "www.nctu.edu.tw", "www.it.nctu.edu.tw", "www.cc.nthu.edu.tw" };
Console.WriteLine("各單位網頁數量,統計時間:" + System.DateTime.Now.ToString());
for (int i = 0; i < 3; i++)
{
HtmlWeb hweb = new HtmlWeb();
HtmlDocument hdoc = hweb.Load("http://www.google.com/search?q=site:" + weblist[i]);
var hnode = hdoc.DocumentNode.Descendants().Single(x => x.Id == "resultStats");
Console.WriteLine(weblist[i] + " = " + hnode.InnerText);
}
Console.ReadLine();
}
}
}
執行結果
比對一下,以清大計中為例,其網頁數量為 817 筆,跟直接用 google 搜尋出來的結果是一樣的。
以這個程式,後續使用只需要修改 weblist 陣列內的網站網址,與迴圈 i 的範圍即可。
~End