[XPATH][ROBOT]常用語法

  • 474
  • 0
  • 2018-04-13

[XPATH][ROBOT]常用語法

直接nuget下載HtmlAgilityPack
直接下載
然後開一個console專案輸入以下內容:

using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestXPath
{
    class Program
    {
        static void Main(string[] args)
        {
            HtmlWeb web;
            HtmlDocument doc = new HtmlDocument();;
            HtmlNodeCollection nodes;

            string xp_title = string.Empty;


            web = new HtmlWeb();
            doc = web.Load("http://www.google.com/search?hl=en&q=xpath&oq=XPath");
			//或是要載入自行定義的字串,可以改成這樣寫
			//doc.LoadHtml(yourOwnString);

            xp_title = @"//h3[@class=""r""]";//tag是h3, 而class屬性等於r的節點
            nodes = doc.DocumentNode.SelectNodes(xp_title);
			//如果只要選擇一個node, 可以這樣寫
			//node = doc.DocumentNode.SelectSingleNode(xp_title);
			//string abc = node.InnerText;

            //顯示所有搜尋到的標題的文字
            Console.WriteLine("顯示所有搜尋到的標題的文字:");
            foreach (HtmlNode node in nodes)
            {
                Console.WriteLine(node.InnerText);
                
            }

            //顯示所有搜尋到的超連結
            Console.WriteLine("顯示所有搜尋到的超連結:");
            xp_title = @"//h3[@class='r']/a";//tag是h3, 而(class屬性等於r)的節點下面的超連結
            nodes = doc.DocumentNode.SelectNodes(xp_title);
            foreach (HtmlNode node in nodes)
            {
                Console.WriteLine(node.Attributes["href"].Value);

            }

            Console.WriteLine("再次顯示所有搜尋到的超連結:");

            //contains經測試有的屬性支援:href, 有的不支援:onmousedown, data-href....
            //實務上要是要拿來用的屬性要是可以用就當作賺到,不能用的話,就別太堅持囉
            xp_title = @"//h3[@class='r']/a[contains(@href,'http')]";//超連結的(href屬性包含關鍵字http)的 這個可正常運作

            nodes = doc.DocumentNode.SelectNodes(xp_title);
            
            foreach (HtmlNode node in nodes)
            {
                Console.WriteLine(node.Attributes["href"].Value);

            }


            Console.WriteLine("press any key to continue");
            Console.ReadKey();
        }
    }
}

最後就可以看到抓到google網頁搜尋出來的結果囉,以上每個node節點的屬性也都可順利運用囉


透過chrome的debug功能,選取某元素之後,就可以直接右鍵將xpath複製出來喔,很好用!!
方便以後自己參考用囉

參考資料:
Xpath 語法 - 使用 HtmlAgilityPack 於 C#
[爬蟲] lxml、XPath 常用語法