分類

展開全部 | 收合全部

分類

展開全部 | 收合全部

【Python 網頁爬蟲 #3】python 爬蟲筆記 – 靜態網頁爬蟲,使用 requests + BeautifulSoup (內含範例程式碼)

前言

這篇是我自己之前做「靜態網頁爬蟲」的筆記程式碼,
順便簡介一下靜態跟動態的差別,

  • 靜態:可以當作是單純爬取 html
  • 動態:有時會有與後端互動的網頁,純 html 無法處理到的部分

通常我們都可以對一個網頁按下右鍵「檢視網頁原始碼」,就可以看到網站原始的 html 了!
在「靜態網頁爬蟲」的主題中,我們使用的就是這個 html 進行搜尋
如果有找不到的內容,那很有可能就是「動態網頁爬蟲」的主題。

範例程式碼 (以爬我自己的網站為例)

之前有一個需求,我想要快速大量的取得我網站 leetcode 主題的所有標題,因此我就自己寫了一個爬蟲來爬我的網站。

但寫得比較複雜一點了,其實不是很適合新手學習,
而且使用的套件也不單純,我只是留這邊給我作為筆記使用XD

不過還是可以大概說明一下我在幹嘛:

  • argparse:一個幫我處理 terminal 輸入的套件,有興趣歡迎在我網站搜尋 argparse 的用法,看完就會懂了。

(我也是拿我網站的範例去改出這支程式的)

  • requests:處理網路、網頁相關的請求用
  • BeautifulSoup:排版、取出特定 html 用,是當我們在拿回 requests 後好用的處理套件

(當然你懂了就知道,這個也可以不用,只是方便處理回傳的內容而已)

其他就不先多說明了,要用別人的程式碼前也要先做一點功課XDD,有些段落想用也請先想想在幹嘛,直接複製交作業,真的很容易就知道你是抄的了XDD (畢竟無關的段落太多XD)

import requests
from bs4 import BeautifulSoup
import argparse

def parse_args():
    parser = argparse.ArgumentParser(prog='argparse_template.py', description='Tutorial') 
    parser.add_argument('-l', default="leet", type=str, required=False, help='leet or lint')
    parser.add_argument('-c', default="py", type=str, required=False, help='py or cpp')
    parser.add_argument('--nums', '-n', type=int, required=True, help='no')

    return parser.parse_args()


def generate_string(url, language):
    print(f"\nNow searching for: {url}")
    response = requests.get(url)

    # print(response)
    soup = BeautifulSoup(response.text, "html.parser")
    # print(soup.prettify())  # 排版後 html

    result = soup.find("h1", class_="page-title")
    # print(f"{result}")
    print("find string: \n")
    print(f"{result.text}\n")


    if language == "cpp":
        final_str = f"<a href=\"{url}\" rel=\"noopener\" target=\"_blank\">C++</a>"
    else:
        final_str = f"<a href=\"{url}\" rel=\"noopener\" target=\"_blank\">Python</a>"

    # print(final_str)
    return final_str

def input_problem_number(n):
    if args.l == "lint":
        problem_src = "lintcode"
    else: # default leetcode
        problem_src = "leetcode"

    if args.c == "cpp":
        language = "cpp"
    else:  # default python
        language = "python"

    url = f"https://www.wongwonggoods.com/python/python_leetcode/{problem_src}-{language}-{n}/"

    return generate_string(url, language)


def main():
    problem_number = args.nums
    print(input_problem_number(problem_number))

if __name__ == '__main__':
    args = parse_args()
    main()

Reference

⭐Python 基礎用法 相關文章整理⭐:
1.【Python】python list 清除, 移除內容元素 remove, pop, del, clear相關用法整理 sample code (內含範例程式碼)
2.【Python】寫模組 module、package 總整理 Importing files from different folder
3.【Python】python assert (斷言) 用法 sample code (內含範例程式碼)
4.【Python】python 一行 if else 語法 (one line if else) sample code (內含範例程式碼)
5.【Python】lambda 與 def function 使用方法與比較整理(內含範例程式碼)
6.【Python】python map 使用方法 與 其他寫法比較整理 (內含範例程式碼) sample code
7.【Python】python zip 使用方法 與 其他寫法比較整理 (內含範例程式碼) sample code
⭐Python 字串處理 相關文章整理⭐:
1.【Python】python print 變數的值 & 變數名稱 方法總整理
2.【Python】python string format str.format 總整理
⭐Python 檔案處理 相關文章整理⭐:
1.【Python】python 開關檔範例 與 程式模板 with open / file open sample code
2.【Python】取出檔案名稱 (含副檔名、不含副檔名) os path basename split 取出 檔名 路徑 不要副檔名 sample code
3.【Python】在 python 中利用 os.chmod 更改檔案的權限 chmod 777
4.【Python】利用 shutil 來複製檔案 shutil copy file
5.【Python】python 建立資料夾範例 mkdir os.makedirs() sample code
6.【Python】python 移除資料夾範例 rmdir shutil.rmtree() sample code
7.【Python】確認檔案是否存在 os.path.isfile / 確認資料夾是否存在 os.path.isdir sample code is folder / file exist
⭐Python 系統偵測 相關文章整理⭐:
1.【Python】python pyinotify sample code 偵測指定路徑底下的文件變化 (內有範例程式碼)
2.【Python】python 利用 argparse 使程式執行時可帶參數 (內附範例程式碼) sample code
⭐Python 平行運算 相關文章整理⭐:
1.【Python】threading – 建立多執行緒來執行程式 (內含範例程式碼) sample code
2.【Python】multiprocessing – 01 | 用多核心來執行程式 (內含範例程式碼) sample code
3.【Python】multiprocessing – 02 | pool, map, apply_async – 用多核心來執行程式並取得結果 (內含範例程式碼) sample code
4.【Python】python thread multiprocess 比較總整理
5.【Python】python pooling multiprocess – 用多核心來執行程式 sample code (內含範例程式碼)
⭐Python 測試程式 相關文章整理⭐:
1.【Python】python 測試程式 – 利用 doctest 測試 python testcase 的優雅寫法,適用於 leetcode (doctest in function,搭配 function 的用法)
2.【Leetcode】python – 利用 doctest 測試 leetcode python testcase 的優雅寫法 (doctest in class,搭配 class 的用法)
⭐Python Chatbot 相關文章整理⭐:
1.【Chatbot】(全圖文說明) LINE Developers bot 機器人註冊與設定
2.【Chatbot】(全圖文說明) ngrok 本地伺服器設定方法 – LINE bot local server
3.【Chatbot】Dialogflow API 串接 python 的方法 (內含範例程式碼)
4.【Chatbot】[講義分享] 手把手實作line機器人 (linebot API 運用)
⭐Python Google Colab (Colaboratory) 相關文章整理⭐:
1.【Colab】Python colab 上傳檔案的方法 (內含範例程式碼) upload files
2.【Colab】Python colab 連接 google 雲端硬碟取用資料 (內含範例程式碼) mount google drive
⭐Python 其他筆記 相關文章整理⭐:
1.【Python】anaconda 更新 (upgrade) python 3.8 版本筆記
2.【Sublime】Sublime 將縮排 “tab” 改成 4格空白 的方法 (圖文說明) sublime indent 4 spaces
3.【Sublime】Python 縮排小技巧 (很爛但實用) 快速將 tab 改成「4格空白」的方法
⭐【喜歡我的文章嗎? 歡迎幫我按讚~ 讓基金會請創作者喝一杯咖啡!
如果喜歡我的文章,請幫我在下方【按五下Like】 (Google, Facebook 免註冊),會由 「LikeCoin」 贊助作者鼓勵繼續創作,讀者們「只需幫忙按讚,完全不用出錢」哦!

likecoin-steps
Howard Weng
Howard Weng

我是 Howard Weng,很多人叫我嗡嗡。這個網站放了我的各種筆記。希望這些筆記也能順便幫助到有需要的人們!如果文章有幫助到你的話,歡迎幫我點讚哦!
另外,因為定位是「個人的隨手筆記」,有些文章內容「⚠️可能我理解有誤⚠️」或「?只寫到一半?」,如果有發現這樣的情況,歡迎在該文章的最下面留言提醒我!我會儘快修正或補上!感謝大家的建議與幫忙,讓網站能變得更好?

文章: 890

★留個言吧!內容有誤或想要補充也歡迎與我討論!