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 New
    • 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 Note Insights Versions and GitHub Sync 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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 5. Python BeautifulSoup套件 ###### tags: `2022資工營` ## BeautifulSoup套件 剛才抓到了HTML原始碼,但並不是所有資料都是我們想要的,這時就需要一個工具幫我們篩選出我們要的資料。BeautifulSoup就是Python一個用來解析HTML原始碼的套件。 回到前面`!pip list`的程式碼區塊,發現BeautifulSoup套件也已經載好了。 ![](https://i.imgur.com/2Pr7K9a.png) 和剛才一樣,新增一個程式碼區塊,貼上`from bs4 import BeautifulSoup`,就可以引用BeautifulSoup套件了。 ## DOM tree BeautifulSoup解析HTML後,會返回一個HTML的DOM tree物件,我們先來講什麼是DOM tree。 **DOM**全名為**Document Object Model**,中文是**文件物件模型**。實際上就是將所有HTML所有的元素(包括文字、圖片、容器)視作樹上的節點,最後結合成樹狀的結構,就像下圖這樣。 ![](https://i.imgur.com/Lc0qR1g.png) 通常有四種節點: * **Document**:所有HTML文件的起點,就像是樹的樹根。 * **Element**:所有的元素,像是`<body>`、`<p>`都是。 * **Text**:被元素所包起來的文字。 * **Attribute**:元素所擁有的屬性,像是`class`、`style`等等。 節點底下包含的節點我們稱為該節點的子節點,而上一層的節點稱為該節點的父節點。 所以說上圖`<body>`的子節點是`<a>`和`<h1>`,而父節點是`<html>`。 ## 解析HTML BeautifulSoup有提供兩種解析器,一種是`html.parser`,另一種是`xml`,因為現在抓到的是HTML,所以選`html.parser`。 解析完後回傳的是DOM tree的根節點(document),我們可以從根節點出發,搜尋他底下的所有子節點。 `prettify()`這個函數可以將DOM tree以比較美觀的方式印出。 ```python import requests from bs4 import BeautifulSoup url = "https://andychiangsh.github.io/python-spider-tutorial/web/" # 取得大資工網頁的HTML原始碼 response = requests.get(url) root = BeautifulSoup(response.text, "html.parser") # 解析原始碼 print(root.prettify()) # 美化輸出 ``` ## 定位節點 原始碼解析完後是一個樹狀的結構,每一個標籤都代表了一個節點,我們要先定位到想要的節點後,才能取得他的文字或屬性。再來會講提供四種定位方法: 補充一下,如果想要知道網頁中的某個元素的HTML原始碼,只要對那個元素**點右鍵**,然後按**檢查**,右側出現的開發人員選單就會顯示該元素的位置了。 ### find() 定位符合標籤的**第一個節點**。 ```python h1 = root.find("h1") print(h1) ``` ``` <h1 class="me-3 fw-bold">中興大資工系</h1> ``` ### find_all() 定位符合標籤的**所有節點**,回傳的是一個列表(List)。 ```python h2s = root.find_all("h2") print(h2s) # 列表 print(h2s[0]) # 使用索引值取得第一個元素 ``` ``` [<h2 class="fw-bold">NCHU CSE</h2>, <h2 class="this" id="this">系所介紹</h2>, <h2>課程介紹</h2>] <h2 class="fw-bold">NCHU CSE</h2> ``` 如果想定位多個標籤,則將標籤打包成一個列表就好了。limit屬性則可以限制數量。 ```python h1_h2s = root.find_all(["h1", "h2"], limit=3) print(h1_h2s) print(len(h1_h2s)) ``` ``` [<h1 class="me-3 fw-bold">中興大資工系</h1>, <h2 class="fw-bold">NCHU CSE</h2>, <h2 class="this" id="this">系所介紹</h2>] 3 ``` `find()`和`find_all()`都可以篩選指定的屬性值。 使用`class`屬性定位,但因為在Python中已經有`class`保留字了,所以改用`class_`。 ```python h2 = root.find("h2", class_="this") print(h2) ``` ``` <h2 class="this" id="this">系所介紹</h2> ``` 當然用id屬性定位也沒問題。 ```python h2 = root.find("h2", id="this") print(h2) ``` ``` <h2 class="this" id="this">系所介紹</h2> ``` ### select_one() 其實和`find()`相似,不過`select_one()`是用CSS選擇器的語法做搜尋。 ```python # 等同於root.find("h1") h1 = root.select_one("h1") print(h1) # 等同於root.find("h2", class_="this") h2 = root.select_one("h2.this") print(h2) # 等同於root.find("h2", id="this") h2 = root.select_one("h2#this") print(h2) ``` ``` <h1 class="me-3 fw-bold">中興大資工系</h1> <h2 class="this" id="this">系所介紹</h2> <h2 class="this" id="this">系所介紹</h2> ``` ### select() 其實就是使用CSS選擇器語法的`find_all()`啦。回傳也是一個列表。 ```python # 等同於root.find_all("h2") h2s = root.select("h2") print(h2s) print(h2s[0]) ``` ``` [<h2 class="fw-bold">NCHU CSE</h2>, <h2 class="this" id="this">系所介紹</h2>, <h2>課程介紹</h2>] <h2 class="fw-bold">NCHU CSE</h2> ``` ## 移動節點 定位好一個節點後,可以用一些函數移動到他的子節點或父節點。 ### find_parent() 移動到該節點的父節點(上一層)。 我們先找到紅色那堂課(id為here),然後移動到他的父節點,也就是整個清單。 ```python here = root.find("li", id="here") print(here) ``` ``` <li id="here">機率</li> ``` ```python parent = here.find_parent() print(parent) ``` ``` <ul class="grade1"> <li>離散數學</li> <li id="here">機率</li> <li>統計學</li> <li>基礎程式設計</li> <li>物件導向程式設計</li> </ul> ``` ### find_previous_sibling() 找到和該節點同層級的上一個節點。 ```python pre_sibling = here.find_previous_sibling() print(pre_sibling) ``` ``` <li>離散數學</li> ``` ### find_next_sibling() 找到和該節點同層級的下一個節點。 ```python next_sibling = here.find_next_sibling() print(next_sibling) ``` ``` <li>統計學</li> ``` ### 移動到子節點 如果是想要移動到該節點底下的子節點,就直接從該節點再往下搜尋一次就好了。 比方說:我想要找class為info的`<div>`底下的`<p>`,程式就會寫成這樣: ```python # 先找<div>再找<p> info_p = root.find("div", class_="info").find("p") print(info_p) ``` ``` <p> 資訊科技產業為我國最重要的產業之一,本系身為中部唯一頂尖大學的資訊系所,當以培養國家尖端資訊產業人才為職志。為培養具備資訊理論、硬體、軟體、網路多媒 體與資訊應用之全方位資訊人才,本系課程規劃以下列五大領域為重點特色:網路多媒體、嵌入式系統、智慧型系統、物聯網與雲端運算以及資訊安全。 </p> ``` ## 小試身手0 試著利用剛才學的技巧,從這個網站中找出中興大資工系大三有哪些課,其中第二堂課叫什麼? > Hint: 需要搜尋兩次 ## 取得文字 定位到指定的節點後,可以使用`text`取得文字。 ```python h1 = root.find("h1") print(h1.text) ``` ``` 中興大資工系 ``` ## 取得屬性值 對於有屬性值的節點,就用類似字典的方式`節點["屬性"]`取得屬性值。 例如我要取得`<img>`標籤中的src屬性值: ```python img = root.find("img") print(img["src"]) ``` ``` https://andychiangsh.github.io/python-spider-tutorial/web/img/logo.jpg ``` 或者取得底下中興資工系官網的連結網址: ```python link = root.find("a") print(link["href"]) ``` ``` http://www.cs.nchu.edu.tw/v4/ ``` ## 下載圖片 爬蟲除了取得文字外,甚至可以幫你下載圖片哦! 首先我們必須知道圖片存放的網址,也就是剛才`<img>`的**src屬性**。知道網址後,就可以對該網址送出請求,回傳是一個response的物件,其中content屬性就是圖片資料了。 接著用Python內建的方式存檔,因為圖片實際上是由一個個像素所組成的二進位資料(Pygame會教),因此存檔的模式要選擇 **wb(write+binary)**。 ```python # 下載圖片 img = root.find("img") # 定位img response = requests.get(img["src"]) # 取得src屬性 with open("logo.jpg", "wb") as file: file.write(response.content) # 寫入檔案 ``` 執行過後就會發現你的資料夾中已經有中興大資工系的Logo了~ ![](https://i.imgur.com/4FBmqae.png) 點兩下可以預覽圖片,也可以下載下來。

    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