HuiXillya
    • 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
    # python 爬蟲 ###### *ps:本篇內容可能含有我的個人資料,請當作沒看到:P ## http運作原理* http **H**yper **T**ext **T**ransform **P**rotocol **超文字傳輸協定** 以簡易層面的理解 ![](https://i.imgur.com/YqM4ovQ.png) ![](https://miro.medium.com/max/875/0*s2u2kEx-8rAhxGaW) 送出request 獲得respones 所以我們專注的點會在於送出甚麼requet與解析獲得的respones ### request request 的方法在 http1.1中有八種,不過最常見的方法為get 與 post GET vs POST Method 先舉個例子,如果 HTTP 代表現在我們現實生活中寄信的機制,那麼信封的撰寫格式就是 HTTP。我們姑且將信封外的內容稱為 http-header,信封內的書信稱為 message-body,那麼 HTTP Method 就是你要告訴郵差的寄信規則。 假設 GET 表示信封內不得裝信件的寄送方式,如同是明信片一樣(感謝網友 Kevin 的建議,採用明信片來詮釋 GET),你可以把要傳遞的資訊寫在信封(http-header)上,寫滿為止,價格比較便宜。然而 POST 就是信封內有裝信件的寄送方式(信封有內容物),不但信封可以寫東西,信封內 (message-body) 還可以置入你想要寄送的資料或檔案,價格較貴。 使用 GET 的時候我們直接將要傳送的資料以 Query String(一種Key/Vaule的編碼方式)加在我們要寄送的地址(URL)後面,然後交給郵差傳送。使用 POST 的時候則是將寄送地址(URL)寫在信封上,另外將要傳送的資料寫在另一張信紙後,將信紙放到信封裡面,交給郵差傳送。 [取自](https://blog.toright.com/posts/1203/%E6%B7%BA%E8%AB%87-http-method%EF%BC%9A%E8%A1%A8%E5%96%AE%E4%B8%AD%E7%9A%84-get-%E8%88%87-post-%E6%9C%89%E4%BB%80%E9%BA%BC%E5%B7%AE%E5%88%A5%EF%BC%9F.html)<-當你按下他,你就是在GET ### header ### cookies 因為HTTP屬於Stateless Connection(無狀態式連結),每個URL的HTTP請求都需與Web Server建立連結,但處理結束並將結果回應(response)至用戶端Web Browser後便立即終止通訊連結。 所以如果想要讓Server端認知我們的狀態,我們需要讓serever在我們電腦中儲存一點點資料,並且在下次request在header中一起送出 這一小點點資料就像一塊小餅乾,所以較cookie(聽說ㄉ) ### respones respones為伺服器回傳的資料,bytes組成,所以在我們client必須進行解碼我們才看得懂(無論是人還是電腦),目前常見的文字檔(text)的部分編碼為ACSII 與 UTF-8 還有big-5(繁體中文限定,逐漸邊緣中) ## Let's start! 我們將以爬ptt八卦版為例 廢話不多說,直接看code ```python= # coding=utf-8 import bs4 import requests def savehtm(data,floder): file = open(floder, 'w', encoding = 'UTF-8') file.write(data) file.close() #data url='https://www.ptt.cc/bbs/Gossiping/index.html' headers={ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0' } cookies={ 'over18':'1' } #opreat respone=requests.get(url,cookies=cookies,headers=headers) respone.encoding='utf-8' root=bs4.BeautifulSoup(respone.text,'html.parser') print(root) ``` ### 函式庫 首先我們需要 requests 和 beautifulsoup4 安裝好後import他們 ```python= import requests import beautifulsoup4 ``` #### requests https://requests.readthedocs.io/en/master/ #### bs4 用來解析網頁內容的套件 https://www.crummy.com/software/BeautifulSoup/bs4/doc/ ### request 我們需要的東西有 1 url 2 cookie 3 header 並且把他們包在一起然後送出去 然後以八卦版為例 所以url='https://www.ptt.cc/bbs/Gossiping/index.html' #### header ![](https://i.imgur.com/8IfjCqH.png) 這是我們瀏覽器平常送出的headers 想偽裝成瀏覽器我們就要上面的header送 不過八卦版疑似不送header也不會擋 #### cookie 一般來說,一開始進入八卦版通常都要回答"是否大於18歲",而第二次則會讓你直接進去,我們可以藉由觀察來發現我們的cookie多ㄌ一個over18 的東西 ### respones 一班來說我們要分析的就是網頁的文字部分 ```python= respone=requests.get(url,cookies=cookies,headers=headers) respone.encoding='utf-8'#通常他會設utf-8,不過需要更改時就能這樣更改 print(respones.text) ``` text的部分即為網頁的文字部分 ### 分析 接下來我們會拿到的東西通常是長這樣 ![](https://i.imgur.com/5YmvORM.png) (節錄) 然後就把這些丟給bs4解析 ```python= root=bs4.BeautifulSoup(respone.text,'html.parser') #html.parser闈內建之解析器 ``` 以標題為例,之後如果我們要蒐集的是標題的話 可以觀察到標題都是屬於 ```htmlmixed= <div class="title"> <a href="link_of_the_title">[標題]我是標題</a> </div> ``` 當我們要找到這些資料時 ```python= titles=root.find_all('div',class_='title') for i in range(len(titles)): titles[i]=titles[i].a #titles[i]=titles[i].find('a') print(titles[i].string) ``` find_all()是找出所有相符的 find()是找出第一個符合的 接下來我們的資料就會長這樣 ```htmlmixed= <a href="link_of_the_title">[標題]我是標題</a> ``` ```python= print(titles[0].string) #輸出:[標題]我是標題 print(titles[0].get('href')) #輸出:link_of_the_title ``` #### 下一頁? 如果想要多爬幾頁,我們就須找到"下一頁"的連結 在ptt則是上頁,所以我們需要找到他 ```htmlmixed= <a class="btn wide" href="/bbs/Gossiping/index39007.html">‹ 上頁</a> ``` python code ```python= nextlink=root.find('div',id='action-bar-container')#這行不寫也行把下面改成root即可 nextlink=nextlink.find('a',string='‹ 上頁')#也可以用內文尋找 nexturl=str(nextlink.get('href')) print(nexturl) #輸出:/bbs/Gossiping/index39007.html ``` 然後我們再加上https://www.ptt.cc 就有下一頁的url了 最後看要把爬網頁寫成funtion然後for loop還是while loop都隨意 ps:有的網頁很好心,網址是流水號直接loop即可 ### 練習 尋找心儀的網站練習吧!另外想爬圖片 403 forbidden 是被發現然後ban掉 404 可能是網頁不存在 ### 課表?(我沒研究出不用登入ㄉ) ```python= # coding=utf-8 import bs4 import requests def savehtm(data,floder): file = open(floder, 'w', encoding = 'UTF-8') file.write(data) file.close() #data url='https://onepiece2-sso.nchu.edu.tw/cofsys/plsql/vocscrd_table' student_id=4109999999 headers={ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0' } cookies={ 'cookie_psstud':str(student_id),'IPCZQX03846e843c':'010090007a76235e9fa4d4e91e4b33047cd63dcc' } #opreat respone=requests.get(url,headers=headers,cookies=cookies) root=bs4.BeautifulSoup(respone.text,'html.parser') print(root) #savehtm(respone.text,'C:\\Users\Hui\Desktop\python-web\myweb.htm') ```

    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