【PTT爬蟲練習】找藝文票券出售,直接抓下來看吧 — 以 Drama — Ticket 版為例

Alan Syue
5 min readMar 24, 2018

( 圖片來源:PTTChrome )

身為一位資深的鄉民,每天掛在 PTT 上是非常正常的,就算地震來襲,也一定要先登入八卦版,看看是不是真的地震,還是被自己抖腳嚇到。

而前陣子因為工作上的需求,我開始研究該如何爬取 PTT 上的資訊。最近剛好想找有沒有人販售我想看場次的票,因此就用爬取 Drama — Ticket 版來跟大家分享一下簡短的練習心得。

不知道從何下手?就從 Web 版的 PTT 開始

由於要從 BBS ( 電子布告欄系統 ) 去爬取,我實在不知道該怎麼做,於是一開始先選定從 Web 版下手。從 Google 搜尋 「 drama ticket ptt 」,就能看到該看板出現在搜尋結果第一條。

點進搜尋結果後,就能獲得我們最需要的第一項條件 — 網址 ( https://www.ptt.cc/bbs/Drama-Ticket/index.html )

找到網址後,先觀察網站架構

這時我們可以來觀察一下,我想要的資訊有兩項,第一個是文章標題,另一個是文章的網址。於是按下 F12,可以發現這兩項資訊放在 < div class = “ title “ > 的 < a > 裡面,我需要取出文字跟網址。

發現目標後,開始寫程式碼吧

在了解完網頁的架構後,讓我們來開始寫出程式碼吧。

步驟一、呼叫 module

先呼叫需要使用到的 module ,這次會使用到的是 BeautifulSoup 和 requests。

import requests

from bs4 import BeautifulSoup

步驟二、利用 requests、BeautifulSoup

接下來我們需要對 Drama — ticket 的網頁做請求,於是我們放上 Drama-Ticket 板的 Web 端網址

html = requests.get(“https://www.ptt.cc/bbs/Drama-Ticket/index.html")

然後我們需要使用 BeautifulSoup 來進行後續網頁處理

soup = BeautifulSoup(html.text,”html5lib”)

步驟三、利用 BeautifulSoup 找出 class = “ title “

接著我們可以用 BeautifulSoup 的 findAll 找出所有含 class = “ title “ 的項目

post_title = soup.findAll(“div”,{“class”:”title”})

步驟四、For 迴圈取出所需要的資訊 ( tilte , url )

首先,我們可以從觀察網站架構時發現,取出內容中的網址並沒有包含主網域,故我們先新增此變數,後續可以讓抓出的網址變得完整。

url_domain =”https://www.ptt.cc"

由於 BeautifulSoup 的 findAll 會抓出所有的內容會並放在 List 中,所以我們要用 for 迴圈取出 post_title 裡的所有項目,再 print 出:

  1. title 的文字
  2. find <a> 裡的網址,並加上 PTT 主網域

for post in post_title:

print(post.text,url_domain+post.find(“a”).get(“href”))

步驟五、查看最後結果

按下執行後,我們就可以看到最後 print 出的結果,包含標題和網址

總結

這次的練習是使用非常簡單的方式,其實還可以做出像持續翻頁得到時間更前面的資料,或者是進到內文獲得需要的資訊,不過因為需要花費的篇幅較多,這次就沒有提到,希望未來能再多分享一些練習的成果,一同交流。

附上完整程式碼:

import requests

from bs4 import BeautifulSoup

html = requests.get(“https://www.ptt.cc/bbs/Drama-Ticket/index.html")soup = BeautifulSoup(html.text,”html5lib”)

post_title = soup.findAll(“div”,{“class”:”title”})

url_domain =”https://www.ptt.cc"

for post in post_title:

print(post.text,url_domain+post.find(“a”).get(“href”))

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Alan Syue
Alan Syue

Written by Alan Syue

Backend Engineer at UPN | Love to share everything

No responses yet

Write a response