首頁 後端開發 Python教學 詳細教學:不使用 API 爬取 GitHub 儲存庫資料夾

詳細教學:不使用 API 爬取 GitHub 儲存庫資料夾

Dec 16, 2024 am 06:28 AM

Detailed Tutorial: Crawling GitHub Repository Folders Without API

超詳細教學:不使用 API 爬取 GitHub 儲存庫資料夾

這個超詳細的教學由 Shpetim Haxhiu 撰寫,將引導您以程式設計方式爬取 GitHub 儲存庫資料夾,而無需依賴 GitHub API。它包括從理解結構到提供具有增強功能的健壯的遞歸實現的所有內容。


1.設定與安裝

開始之前,請確保您已:

  1. Python:已安裝版本 3.7 或更高版本。
  2. :安裝請求和BeautifulSoup。
   pip install requests beautifulsoup4
  1. 編輯器:任何支援 Python 的 IDE,例如 VS Code 或 PyCharm。

2.分析 GitHub HTML 結構

要抓取 GitHub 資料夾,您需要了解儲存庫頁面的 HTML 結構。在 GitHub 儲存庫頁面上:

  • 資料夾 與 /tree// 等路徑連結。
  • 檔案 與 /blob// 等路徑連結。

每個項目(資料夾或檔案)都位於

內具有屬性 role="rowheader" 並包含 ;標籤。例如:
<div role="rowheader">
  <a href="/owner/repo/tree/main/folder-name">folder-name</a>
</div>

3.實作抓取器

3.1。遞歸爬取函數

該腳本將遞歸地抓取資料夾並列印其結構。為了限制遞歸深度並避免不必要的負載,我們將使用深度參數。

import requests
from bs4 import BeautifulSoup
import time

def crawl_github_folder(url, depth=0, max_depth=3):
    """
    Recursively crawls a GitHub repository folder structure.

    Parameters:
    - url (str): URL of the GitHub folder to scrape.
    - depth (int): Current recursion depth.
    - max_depth (int): Maximum depth to recurse.
    """
    if depth > max_depth:
        return

    headers = {"User-Agent": "Mozilla/5.0"}
    response = requests.get(url, headers=headers)

    if response.status_code != 200:
        print(f"Failed to access {url} (Status code: {response.status_code})")
        return

    soup = BeautifulSoup(response.text, 'html.parser')

    # Extract folder and file links
    items = soup.select('div[role="rowheader"] a')

    for item in items:
        item_name = item.text.strip()
        item_url = f"https://github.com{item['href']}"

        if '/tree/' in item_url:
            print(f"{'  ' * depth}Folder: {item_name}")
            crawl_github_folder(item_url, depth + 1, max_depth)
        elif '/blob/' in item_url:
            print(f"{'  ' * depth}File: {item_name}")

# Example usage
if __name__ == "__main__":
    repo_url = "https://github.com/<owner>/<repo>/tree/<branch>/<folder>"
    crawl_github_folder(repo_url)

4.功能解釋

  1. 請求標頭:使用使用者代理字串來模擬瀏覽器並避免阻塞。
  2. 遞歸爬行
    • 偵測資料夾 ​​(/tree/) 並遞歸地輸入它們。
    • 列出檔案 (/blob/),無需進一步輸入。
  3. 縮排:反映輸出中的資料夾層次結構。
  4. 深度限制:透過設定最大深度(max_深度)來防止過度遞歸。

5.增強功能

這些增強功能旨在提高爬蟲程序的功能和可靠性。它們解決了導出結果、處理錯誤和避免速率限制等常見挑戰,確保工具高效且用戶友好。

5.1。匯出結果

將輸出儲存到結構化 JSON 檔案以便於使用。

   pip install requests beautifulsoup4

5.2。錯誤處理

為網路錯誤和意外的 HTML 變更添加強大的錯誤處理:

<div role="rowheader">
  <a href="/owner/repo/tree/main/folder-name">folder-name</a>
</div>

5.3。速率限制

為了避免受到 GitHub 的速率限制,請引入延遲:

import requests
from bs4 import BeautifulSoup
import time

def crawl_github_folder(url, depth=0, max_depth=3):
    """
    Recursively crawls a GitHub repository folder structure.

    Parameters:
    - url (str): URL of the GitHub folder to scrape.
    - depth (int): Current recursion depth.
    - max_depth (int): Maximum depth to recurse.
    """
    if depth > max_depth:
        return

    headers = {"User-Agent": "Mozilla/5.0"}
    response = requests.get(url, headers=headers)

    if response.status_code != 200:
        print(f"Failed to access {url} (Status code: {response.status_code})")
        return

    soup = BeautifulSoup(response.text, 'html.parser')

    # Extract folder and file links
    items = soup.select('div[role="rowheader"] a')

    for item in items:
        item_name = item.text.strip()
        item_url = f"https://github.com{item['href']}"

        if '/tree/' in item_url:
            print(f"{'  ' * depth}Folder: {item_name}")
            crawl_github_folder(item_url, depth + 1, max_depth)
        elif '/blob/' in item_url:
            print(f"{'  ' * depth}File: {item_name}")

# Example usage
if __name__ == "__main__":
    repo_url = "https://github.com/<owner>/<repo>/tree/<branch>/<folder>"
    crawl_github_folder(repo_url)

6.道德考量

由軟體自動化和道德程式設計專家 Shpetim Haxhiu 撰寫,本部分確保在使用 GitHub 爬蟲時遵守最佳實踐。

  • 合規性:遵守 GitHub 的服務條款。
  • 最小化負載:透過限制請求和增加延遲來尊重 GitHub 的伺服器。
  • 權限:取得廣泛爬取私有倉庫的權限。

7.完整程式碼

這是包含所有功能的綜合腳本:

import json

def crawl_to_json(url, depth=0, max_depth=3):
    """Crawls and saves results as JSON."""
    result = {}

    if depth > max_depth:
        return result

    headers = {"User-Agent": "Mozilla/5.0"}
    response = requests.get(url, headers=headers)

    if response.status_code != 200:
        print(f"Failed to access {url}")
        return result

    soup = BeautifulSoup(response.text, 'html.parser')
    items = soup.select('div[role="rowheader"] a')

    for item in items:
        item_name = item.text.strip()
        item_url = f"https://github.com{item['href']}"

        if '/tree/' in item_url:
            result[item_name] = crawl_to_json(item_url, depth + 1, max_depth)
        elif '/blob/' in item_url:
            result[item_name] = "file"

    return result

if __name__ == "__main__":
    repo_url = "https://github.com/<owner>/<repo>/tree/<branch>/<folder>"
    structure = crawl_to_json(repo_url)

    with open("output.json", "w") as file:
        json.dump(structure, file, indent=2)

    print("Repository structure saved to output.json")

透過遵循此詳細指南,您可以建立強大的 GitHub 資料夾爬蟲。該工具可以適應各種需求,同時確保道德合規性。


歡迎在留言區留言!另外,別忘了與我聯絡:

  • 電子郵件:shpetim.h@gmail.com
  • LinkedIn:linkedin.com/in/shpetimhaxhiu
  • GitHub:github.com/shpetimhaxhiu

以上是詳細教學:不使用 API 爬取 GitHub 儲存庫資料夾的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1601
29
PHP教程
1503
276
如何處理Python中的API身份驗證 如何處理Python中的API身份驗證 Jul 13, 2025 am 02:22 AM

處理API認證的關鍵在於理解並正確使用認證方式。 1.APIKey是最簡單的認證方式,通常放在請求頭或URL參數中;2.BasicAuth使用用戶名和密碼進行Base64編碼傳輸,適合內部系統;3.OAuth2需先通過client_id和client_secret獲取Token,再在請求頭中帶上BearerToken;4.為應對Token過期,可封裝Token管理類自動刷新Token;總之,根據文檔選擇合適方式,並安全存儲密鑰信息是關鍵。

如何一次迭代兩個列表 如何一次迭代兩個列表 Jul 09, 2025 am 01:13 AM

在Python中同時遍歷兩個列表的常用方法是使用zip()函數,它會按順序配對多個列表並以最短為準;若列表長度不一致,可使用itertools.zip_longest()以最長為準並填充缺失值;結合enumerate()可同時獲取索引。 1.zip()簡潔實用,適合成對數據迭代;2.zip_longest()處理不一致長度時可填充默認值;3.enumerate(zip())可在遍歷時獲取索引,滿足多種複雜場景需求。

Python Fastapi教程 Python Fastapi教程 Jul 12, 2025 am 02:42 AM

要使用Python創建現代高效的API,推薦使用FastAPI;其基於標準Python類型提示,可自動生成文檔,性能優越。安裝FastAPI和ASGI服務器uvicorn後,即可編寫接口代碼。通過定義路由、編寫處理函數並返回數據,可以快速構建API。 FastAPI支持多種HTTP方法,並提供自動生成的SwaggerUI和ReDoc文檔系統。 URL參數可通過路徑定義捕獲,查詢參數則通過函數參數設置默認值實現。合理使用Pydantic模型有助於提升開發效率和準確性。

如何用Python測試API 如何用Python測試API Jul 12, 2025 am 02:47 AM

要測試API需使用Python的Requests庫,步驟為安裝庫、發送請求、驗證響應、設置超時與重試。首先通過pipinstallrequests安裝庫;接著用requests.get()或requests.post()等方法發送GET或POST請求;然後檢查response.status_code和response.json()確保返回結果符合預期;最後可添加timeout參數設置超時時間,並結合retrying庫實現自動重試以增強穩定性。

Python函數可變範圍 Python函數可變範圍 Jul 12, 2025 am 02:49 AM

在Python中,函數內部定義的變量是局部變量,僅在函數內有效;外部定義的是全局變量,可在任何地方讀取。 1.局部變量隨函數執行結束被銷毀;2.函數可訪問全局變量但不能直接修改,需用global關鍵字;3.嵌套函數中若要修改外層函數變量,需使用nonlocal關鍵字;4.同名變量在不同作用域互不影響;5.修改全局變量時必須聲明global,否則會引發UnboundLocalError錯誤。理解這些規則有助於避免bug並寫出更可靠的函數。

如何用Python和Pandas解析HTML表 如何用Python和Pandas解析HTML表 Jul 10, 2025 pm 01:39 PM

是的,你可以使用Python和Pandas解析HTML表格。首先,使用pandas.read_html()函數提取表格,該函數可將網頁或字符串中的HTML元素解析為DataFrame列表;接著,若表格無明確列標題,可通過指定header參數或手動設置.columns屬性修復;對於復雜頁面,可結合requests庫獲取HTML內容或使用BeautifulSoup定位特定表格;注意JavaScript渲染、編碼問題及多表識別等常見陷阱。

在Python中訪問嵌套的JSON對象 在Python中訪問嵌套的JSON對象 Jul 11, 2025 am 02:36 AM

在Python中訪問嵌套JSON對象的方法是先明確結構,再逐層索引。首先確認JSON的層級關係,例如字典嵌套字典或列表;接著使用字典鍵和列表索引逐層訪問,如data"details"["zip"]獲取zip編碼,data"details"[0]獲取第一個愛好;為避免KeyError和IndexError,可用.get()方法設置默認值,或封裝函數safe_get實現安全訪問;對於復雜結構,可遞歸查找或使用第三方庫如jmespath處理。

python def vs lambda Deep Dive python def vs lambda Deep Dive Jul 10, 2025 pm 01:45 PM

def適用於復雜函數,支持多行、文檔字符串和嵌套;lambda適合簡單匿名函數,常用於參數傳函數的場景。選def的情況:①函數體多行;②需文檔說明;③被多處調用。選lambda的情況:①一次性使用;②無需名字或文檔;③邏輯簡單。注意lambda延遲綁定變量可能引發錯誤,且不支持默認參數、生成器或異步。實際應用中根據需求靈活選擇,清晰優先。

See all articles