# [golang] 爬蟲繞過 ptt 限制級警告 > [time=Aug 14, 2024] 最近在學習 Golang,同時也順便學習一點簡單的爬蟲要怎麼寫,PTT 網頁版是個滿適合練習的地方,結構單純且似乎比較沒在擋爬蟲。 PTT 有某些看板被設定成限制級,在網頁版瀏覽時需點選已年滿十八歲才可進入看板閱讀文章,例如八卦板,以及最近因為 iwin 事件而被投票改成限制級看板的希洽板[1]。 我們利用 Chrome DevTools 觀察一下行為可以發現點擊「我同意,我已年滿十八歲」後會發送一個 POST request,而 response 會設定 cookie 值 `over18=1`,並轉址至看板頁面。 以下為簡單的 go 程式碼範例,使用到 Colly 這個爬蟲框架。 :::info 環境: - Go 1.22.6 - [Colly](https://github.com/gocolly/colly) ::: ## 方法一:發送 POST request ```go= c.Post("https://www.ptt.cc/ask/over18", map[string]string{ "from": "/bbs/C_Chat/index.html", "yes": "yes", }) ``` ## 方法二:直接設定 HTTP cookie ```go= c.OnRequest(func(request *colly.Request) { request.Headers.Set("Cookie", "over18=1") }) ``` ## 完整程式碼 ```go= package main import ( "fmt" "github.com/gocolly/colly/v2" ) func main() { c := colly.NewCollector() // 方法一 c.Post("https://www.ptt.cc/ask/over18", map[string]string{ "from": "/bbs/C_Chat/index.html", "yes": "yes", }) // 方法二 c.OnRequest(func(req *colly.Request) { req.Headers.Set("Cookie", "over18=1") }) // 若將以上方法都註解掉就會印出限制級警告訊息 c.OnHTML("div.over18-notice", func(e *colly.HTMLElement) { fmt.Println(e.Text) }) // 成功的話會印出看板第一頁的文章標題 c.OnHTML("div.title", func(e *colly.HTMLElement) { e.ForEach("a", func(i int, a *colly.HTMLElement) { fmt.Println(a.Text) }) }) c.Visit("https://www.ptt.cc/bbs/C_Chat/index.html") } ``` ## References - [1] [[公告] C_Chat自即日起更改分級為限制級看板](https://www.ptt.cc/bbs/C_Chat/M.1708532280.A.47E.html) @ PTT (2024年2月22日) - [Golang 抓取PTT Beauty板網頁資料](https://matthung0807.blogspot.com/2023/01/go-scrape-ptt-web-beauty.html) - [爬蟲極簡教學(fetch, parse, search, multiprocessing, API)- PTT 為例](https://github.com/leVirve/CrawlerTutorial)