AndyChiang
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 6. PTT C_Chat板爬蟲 ###### tags: `2022資工營` 學完怎麼用BeautifulSoup解析HTML後,接著就來實際找個網站來現學現賣一下! 我選PTT當作例子,為什麼要選PTT呢? 因為PTT是很多人使用而且算是相對好爬的網站,很適合當成第一次練習爬蟲的網站。 [PTT C_Chat板網址](https://www.ptt.cc/bbs/C_Chat/index.html) 我們的目標很簡單,就是取得PTT C_Chat板上的**文章標題**(紅框圈起來的部分)。 ![](https://i.imgur.com/cDhHU60.png) ## 文章標題 首先,我們對文章標題**右鍵>>檢查**,右邊會跳出開發人員介面顯示文章標題在原始碼中的位置。 稍微觀察一下,我們會發現所有的文章標題都在`class="title"`的`<div>`中。 ![](https://i.imgur.com/6ESgYZM.png) 所以很簡單,程式碼就這樣寫: ```python import requests from bs4 import BeautifulSoup url = "https://www.ptt.cc/bbs/C_Chat/index.html" response = requests.get(url) # 取得C_Chat的HTML原始碼 root = BeautifulSoup(response.text, "html.parser") # 解析原始碼 links = root.find_all("div", class_="title") # 文章標題 for link in links: # 用for迴圈一次迭代一個元素 print(link.text.strip()) # strip()用來刪除文字前面和後面多餘的空白 ``` 執行結果: ![](https://i.imgur.com/h0wV73r.png) ## 小試身手1 現在請大家舉一反三,取得每篇文章的**作者名稱**(紅框圈起來的部分)。 ![](https://i.imgur.com/5wFRoFL.png) ## 自動換頁 現在雖然可以抓下文章清單中的標題了,但只有第一頁的文章而已,要怎麼樣才能抓其他頁的文章呢?? 想一下,我們想要看上一頁時,會做什麼事? 還不簡單! 當然就是按 "上頁" 按鈕阿! 對上方導覽列的 "上頁" 按鈕**右鍵>>檢查**,上一頁的連結就在`string="‹ 上頁"`的`<a>`中。 ![](https://i.imgur.com/Grhz9gh.png) 可是我們也發現了,連結的**href屬性**並不是完整的網址,只有網域後面的部分而已。 但也沒關係,因為網域部分是固定的所以我們自己加上去就好了。 加進for迴圈中,並每次更新url變數,就可以想抓幾頁就抓幾頁囉~ ```python import requests from bs4 import BeautifulSoup url = "https://www.ptt.cc/bbs/C_Chat/index.html" # 第一頁 for i in range(10): print(f"第{i+1}頁:") # 現在到第幾頁 response = requests.get(url) # 取得C_Chat的HTML原始碼 root = BeautifulSoup(response.text, "html.parser") # 解析原始碼 links = root.find_all("div", class_="title") # 文章標題 for link in links: print(link.text.strip()) # strip()用來刪除文字前面和後面多餘的空白 url = "https://www.ptt.cc/" + root.find("a", string="‹ 上頁")["href"] # 換頁 ``` ## 儲存csv檔 目前都只是將抓到的資料印在小黑窗上,如果之後要用到這些資料做後續分析的話,就很不方便了,所以我們要將資料轉成csv格式並存在電腦中。 **逗號分隔值 (Comma-Separated Values,CSV)**,是一種常見的資料儲存方式,其換行代表一個row,並用逗號區分column。 ![](https://i.imgur.com/CaS2BFP.png) 我們抓取每篇文章的**標題**和**作者**,並存成csv檔。 因為這次要一次取得同一篇文章的標題和作者,所以程式碼要稍微做修改...。 回到PTT,我們可以發現每篇文章都是包在`class="r-ent"`的`<div>`中,**因此我們要先找到所有的文章,在找出每篇文章底下的標題和作者就好了!** ![](https://i.imgur.com/yevNBqK.png) ```python articles = root.find_all("div", class_="r-ent") # 所有文章 for article in articles: title = article.find("div", class_="title").text.strip() # 文章標題 author = article.find("div", class_="author").text # 文章作者 print(title, author) ``` 引用Python的csv套件,並開啟一個新的檔案,檔名為"ptt.csv",`newline=""`才不會多換一行,記得`encoding="utf-8-sig"`,不然會出現亂碼。 接著建立一個csv writer物件,使用該物件的`writerow()`函數寫入資料。 程式執行完後,在資料夾中就會多一個"ptt.csv"檔案啦,打開來看看是不是資料都已經在裡面了! 和前面一樣可以點兩下預覽或下載下來。 ```python import requests from bs4 import BeautifulSoup import csv url = "https://www.ptt.cc/bbs/C_Chat/index.html" # 第一頁 # 開啟csv檔案 with open("ptt.csv", "w", newline="", encoding="utf-8-sig") as csvfile: # 建立 CSV 檔寫入器 writer = csv.writer(csvfile) # 寫入欄位名稱 writer.writerow(["標題", "作者"]) for i in range(10): print(f"第{i+1}頁:") response = requests.get(url) # 取得C_Chat的HTML原始碼 root = BeautifulSoup(response.text, "html.parser") # 解析原始碼 articles = root.find_all("div", class_="r-ent") # 所有文章 for article in articles: title = article.find("div", class_="title").text.strip() # 文章標題 author = article.find("div", class_="author").text # 文章作者 print(title, author) writer.writerow([title, author]) # 寫入一行資料 url = "https://www.ptt.cc/"+root.find("a", string="‹ 上頁")["href"] # 換頁 ``` ![](https://i.imgur.com/bWP0Ig2.png) ## 小試身手2 根據上一張的程式碼,加上一些新的程式,在csv檔多儲存一個**發文時間**的欄位。 ![](https://i.imgur.com/xwcvhY4.png) ## 小試身手3 從PTT中挑一個喜歡的分類看板出來,看看能不能做到一樣的事情~ [PTT熱門分類看板](https://www.ptt.cc/bbs/index.html)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully