国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 後端開發(fā) Python教學(xué) 詳細(xì)教學(xué):不使用 API 爬取 GitHub 儲(chǔ)存庫資料夾

詳細(xì)教學(xué):不使用 API 爬取 GitHub 儲(chǔ)存庫資料夾

Dec 16, 2024 am 06:28 AM

Detailed Tutorial: Crawling GitHub Repository Folders Without API

超詳細(xì)教學(xué):不使用 API 爬取 GitHub 儲(chǔ)存庫資料夾

這個(gè)超詳細(xì)的教學(xué)由 Shpetim Haxhiu 撰寫,將引導(dǎo)您以程式設(shè)計(jì)方式爬取 GitHub 儲(chǔ)存庫資料夾,而無需依賴 GitHub API。它包括從理解結(jié)構(gòu)到提供具有增強(qiáng)功能的健壯的遞歸實(shí)現(xiàn)的所有內(nèi)容。


1.設(shè)定與安裝

開始之前,請(qǐng)確保您已:

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

2.分析 GitHub HTML 結(jié)構(gòu)

要抓取 GitHub 資料夾,您需要了解儲(chǔ)存庫頁面的 HTML 結(jié)構(gòu)。在 GitHub 儲(chǔ)存庫頁面上:

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

每個(gè)項(xiàng)目(資料夾或檔案)都位於

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

3.實(shí)作抓取器

3.1。遞歸爬取函數(shù)

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

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. 請(qǐng)求標(biāo)頭:使用使用者代理字串來模擬瀏覽器並避免阻塞。
  2. 遞歸爬行
    • 偵測(cè)資料夾 ??(/tree/) 並遞歸地輸入它們。
    • 列出檔案 (/blob/),無需進(jìn)一步輸入。
  3. 縮排:反映輸出中的資料夾層次結(jié)構(gòu)。
  4. 深度限制:透過設(shè)定最大深度(max_深度)來防止過度遞歸。

5.增強(qiáng)功能

這些增強(qiáng)功能旨在提高爬蟲程序的功能和可靠性。它們解決了導(dǎo)出結(jié)果、處理錯(cuò)誤和避免速率限制等常見挑戰(zhàn),確保工具高效且用戶友好。

5.1。匯出結(jié)果

將輸出儲(chǔ)存到結(jié)構(gòu)化 JSON 檔案以便於使用。

   pip install requests beautifulsoup4

5.2。錯(cuò)誤處理

為網(wǎng)路錯(cuò)誤和意外的 HTML 變更添加強(qiáng)大的錯(cuò)誤處理:

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

5.3。速率限制

為了避免受到 GitHub 的速率限制,請(qǐng)引入延遲:

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.道德考量

由軟體自動(dòng)化和道德程式設(shè)計(jì)專家 Shpetim Haxhiu 撰寫,本部分確保在使用 GitHub 爬蟲時(shí)遵守最佳實(shí)踐。

  • 合規(guī)性:遵守 GitHub 的服務(wù)條款。
  • 最小化負(fù)載:透過限制請(qǐng)求和增加延遲來尊重 GitHub 的伺服器。
  • 權(quán)限:取得廣泛爬取私有倉庫的權(quán)限。

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")

透過遵循此詳細(xì)指南,您可以建立強(qiáng)大的 GitHub 資料夾爬蟲。該工具可以適應(yīng)各種需求,同時(shí)確保道德合規(guī)性。


歡迎在留言區(qū)留言!另外,別忘了與我聯(lián)絡(luò):

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

以上是詳細(xì)教學(xué):不使用 API 爬取 GitHub 儲(chǔ)存庫資料夾的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

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

Python類中的多態(tài)性 Python類中的多態(tài)性 Jul 05, 2025 am 02:58 AM

多態(tài)是Python面向?qū)ο缶幊讨械暮诵母拍?,指“一種接口,多種實(shí)現(xiàn)”,允許統(tǒng)一處理不同類型的對(duì)象。 1.多態(tài)通過方法重寫實(shí)現(xiàn),子類可重新定義父類方法,如Animal類的speak()方法在Dog和Cat子類中有不同實(shí)現(xiàn)。 2.多態(tài)的實(shí)際用途包括簡(jiǎn)化代碼結(jié)構(gòu)、增強(qiáng)可擴(kuò)展性,例如圖形繪製程序中統(tǒng)一調(diào)用draw()方法,或遊戲開發(fā)中處理不同角色的共同行為。 3.Python實(shí)現(xiàn)多態(tài)需滿足:父類定義方法,子類重寫該方法,但不要求繼承同一父類,只要對(duì)象實(shí)現(xiàn)相同方法即可,這稱為“鴨子類型”。 4.注意事項(xiàng)包括保持方

我如何寫一個(gè)簡(jiǎn)單的'你好,世界!” Python的程序? 我如何寫一個(gè)簡(jiǎn)單的'你好,世界!” Python的程序? Jun 24, 2025 am 12:45 AM

"Hello,World!"程序是用Python編寫的最基礎(chǔ)示例,用於展示基本語法並驗(yàn)證開發(fā)環(huán)境是否正確配置。 1.它通過一行代碼print("Hello,World!")實(shí)現(xiàn),運(yùn)行後會(huì)在控制臺(tái)輸出指定文本;2.運(yùn)行步驟包括安裝Python、使用文本編輯器編寫代碼、保存為.py文件、在終端執(zhí)行該文件;3.常見錯(cuò)誤有遺漏括號(hào)或引號(hào)、誤用大寫Print、未保存為.py格式以及運(yùn)行環(huán)境錯(cuò)誤;4.可選工具包括本地文本編輯器 終端、在線編輯器(如replit.com)

Python中的算法是什麼?為什麼它們很重要? Python中的算法是什麼?為什麼它們很重要? Jun 24, 2025 am 12:43 AM

AlgorithmsinPythonareessentialforefficientproblem-solvinginprogramming.Theyarestep-by-stepproceduresusedtosolvetaskslikesorting,searching,anddatamanipulation.Commontypesincludesortingalgorithmslikequicksort,searchingalgorithmslikebinarysearch,andgrap

什麼是python的列表切片? 什麼是python的列表切片? Jun 29, 2025 am 02:15 AM

ListslicinginPythonextractsaportionofalistusingindices.1.Itusesthesyntaxlist[start:end:step],wherestartisinclusive,endisexclusive,andstepdefinestheinterval.2.Ifstartorendareomitted,Pythondefaultstothebeginningorendofthelist.3.Commonusesincludegetting

python`@classmethod'裝飾師解釋了 python`@classmethod'裝飾師解釋了 Jul 04, 2025 am 03:26 AM

類方法是Python中通過@classmethod裝飾器定義的方法,其第一個(gè)參數(shù)為類本身(cls),用於訪問或修改類狀態(tài)。它可通過類或?qū)嵗{(diào)用,影響的是整個(gè)類而非特定實(shí)例;例如在Person類中,show_count()方法統(tǒng)計(jì)創(chuàng)建的對(duì)像數(shù)量;定義類方法時(shí)需使用@classmethod裝飾器並將首參命名為cls,如change_var(new_value)方法可修改類變量;類方法與實(shí)例方法(self參數(shù))、靜態(tài)方法(無自動(dòng)參數(shù))不同,適用於工廠方法、替代構(gòu)造函數(shù)及管理類變量等場(chǎng)景;常見用途包括從

Python函數(shù)參數(shù)和參數(shù) Python函數(shù)參數(shù)和參數(shù) Jul 04, 2025 am 03:26 AM

參數(shù)(parameters)是定義函數(shù)時(shí)的佔(zhàn)位符,而傳參(arguments)是調(diào)用時(shí)傳入的具體值。 1.位置參數(shù)需按順序傳遞,順序錯(cuò)誤會(huì)導(dǎo)致結(jié)果錯(cuò)誤;2.關(guān)鍵字參數(shù)通過參數(shù)名指定,可改變順序且提高可讀性;3.默認(rèn)參數(shù)值在定義時(shí)賦值,避免重複代碼,但應(yīng)避免使用可變對(duì)像作為默認(rèn)值;4.args和*kwargs可處理不定數(shù)量的參數(shù),適用於通用接口或裝飾器,但應(yīng)謹(jǐn)慎使用以保持可讀性。

如何使用CSV模塊在Python中使用CSV文件? 如何使用CSV模塊在Python中使用CSV文件? Jun 25, 2025 am 01:03 AM

Python的csv模塊提供了讀寫CSV文件的簡(jiǎn)單方法。 1.讀取CSV文件時(shí),可使用csv.reader()逐行讀取,並將每行數(shù)據(jù)作為字符串列表返回;若需通過列名訪問數(shù)據(jù),則可用csv.DictReader(),它將每行映射為字典。 2.寫入CSV文件時(shí),使用csv.writer()並調(diào)用writerow()或writerows()方法寫入單行或多行數(shù)據(jù);若要寫入字典數(shù)據(jù),則使用csv.DictWriter(),需先定義列名並通過writeheader()寫入表頭。 3.處理邊緣情況時(shí),模塊自動(dòng)處理

解釋Python發(fā)電機(jī)和迭代器。 解釋Python發(fā)電機(jī)和迭代器。 Jul 05, 2025 am 02:55 AM

迭代器是實(shí)現(xiàn)__iter__()和__next__()方法的對(duì)象,生成器是簡(jiǎn)化版的迭代器,通過yield關(guān)鍵字自動(dòng)實(shí)現(xiàn)這些方法。 1.迭代器每次調(diào)用next()返回一個(gè)元素,無更多元素時(shí)拋出StopIteration異常。 2.生成器通過函數(shù)定義,使用yield按需生成數(shù)據(jù),節(jié)省內(nèi)存且支持無限序列。 3.處理已有集合時(shí)用迭代器,動(dòng)態(tài)生成大數(shù)據(jù)或需惰性求值時(shí)用生成器,如讀取大文件時(shí)逐行加載。注意:列表等可迭代對(duì)像不是迭代器,迭代器到盡頭後需重新創(chuàng)建,生成器只能遍歷一次。

See all articles