C# 爬蟲 含 cookie設定

主要是參考 https://dotblogs.com.tw/Lance_Blog/2019/03/10/114838#google_vignette

首先要下載 HtmlAgilityPack 在 Nuget中有








接著設定 Request 和 Response

這邊是採用PTT的表特版來當作操作方法

    //取 url 可以任意更改

    Uri url = new Uri("https://www.ptt.cc/bbs/beauty/index.html");


    #region 設定是否有搜尋條件等

    string search = "www";

    url = new Uri($"https://www.ptt.cc/bbs/Beauty/search?q={search}");

    #endregion


    //建立request

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

    //設定request 方法

    req.Method = "POST";

    //設定cookies 某些網站可能有防止機制

    _cookies.SetCookies(url, "over18=1");

    req.CookieContainer = _cookies;

接著中間有一部分是關於 Cookies的設定

如果未設定的話


會呈現這個樣子 因為你爬回來的東西是他的未成年防護 而不是主要內容頁面

關於Cookie設定

建立cookies

CookieContainer _cookies = new CookieContainer();

設定

     _cookies.SetCookies(url, "over18=1");

寫入

    req.CookieContainer = _cookies;

接著取得資料後呈現


    //取得資料

    HttpWebResponse res = (HttpWebResponse)req.GetResponse();

    var stream = res.GetResponseStream();


    //走訪資料

    using (var reader = new StreamReader(stream))

    {

        //讀取資料 HTML代碼

        string html = reader.ReadToEnd();

        //丟入Document中 供讀取

        var doc1 = new HtmlDocument();

        doc1.LoadHtml(html);

    }

主要資料在doc1中 轉換成htmlDocument讀取


接著取得目標的xpath


這樣可以取得一串字串 比如 //*[@id="main-container"]/div[2]/div[{i}]/div[2]/a

丟入

doc1.DocumentNode.SelectNodes($"//*[@id='main-container']/div[2]/div[{i}]/div[2]/a") 可以取得Node陣列 通常是都只取一個

 因此

doc1.DocumentNode.SelectNodes($"//*[@id='main-container']/div[2]/div[{i}]/div[2]/a")[0] 就可以取得資料了

然後在自己判斷哪個div需要依照需求去更換取值 大致上就是這樣完成一個爬蟲





//程式碼部分

CookieContainer _cookies = new CookieContainer();

 void ClearCookie()

{

    _cookies = new CookieContainer();

}


void WebLoad()

{

    //取 url 可以任意更改

    Uri url = new Uri("https://www.ptt.cc/bbs/beauty/index.html");


    #region 設定是否有搜尋條件等

    string search = "www";

    url = new Uri($"https://www.ptt.cc/bbs/Beauty/search?q={search}");

    #endregion


    //建立request

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

    //設定request 方法

    req.Method = "POST";

    //設定cookies 某些網站可能有防止機制

    _cookies.SetCookies(url, "over18=1");

    req.CookieContainer = _cookies;

    //取得資料

    HttpWebResponse res = (HttpWebResponse)req.GetResponse();

    var stream = res.GetResponseStream();


    //走訪資料

    using (var reader = new StreamReader(stream))

    {

        //讀取資料 HTML代碼

        string html = reader.ReadToEnd();

        //丟入Document中 供讀取

        var doc1 = new HtmlDocument();

        doc1.LoadHtml(html);


        #region 爬資料

        List<string> title = new List<string>();

        List<string> author = new List<string>();

        List<string> date = new List<string>();

        //控制筆數

        for (int i = 2; i < 100; i++)

        {

            //取xpath 令附圖支援

            if (doc1.DocumentNode.SelectNodes($"//*[@id='main-container']/div[2]/div[{i}]/div[2]/a") != null)

            {

                title.Add(

                    doc1.DocumentNode.SelectNodes($"//*[@id='main-container']/div[2]/div[{i}]/div[2]/a") == null ?

                    "" : doc1.DocumentNode.SelectNodes($"//*[@id='main-container']/div[2]/div[{i}]/div[2]/a")[0].InnerText);

                author.Add(

                    doc1.DocumentNode.SelectNodes($"//*[@id=\'main-container\']/div[2]/div[{i}]/div[3]/div[1]") == null ? "" :

                    doc1.DocumentNode.SelectNodes($"//*[@id=\'main-container\']/div[2]/div[{i}]/div[3]/div[1]")[0].InnerText);

                date.Add(

                    doc1.DocumentNode.SelectNodes($"//*[@id=\'main-container\']/div[2]/div[{i}]/div[3]/div[3]") == null ? "" :

                    doc1.DocumentNode.SelectNodes($"//*[@id=\'main-container\']/div[2]/div[{i}]/div[3]/div[3]")[0].InnerText);

            }

            else break;

        }

        #endregion

    }

}


參考:

https://ithelp.ithome.com.tw/articles/10204709

https://igouist.github.io/post/2022/06/angle-sharp/

https://dotblogs.com.tw/Lance_Blog/2019/03/10/114838#google_vignette

留言

這個網誌中的熱門文章

無法載入檔案或組件 'System.IO.Compression' 或其相依性的其中之一。

MongoDB 入門

javascript 更改屬性及創建標籤