찾다
백엔드 개발파이썬 튜토리얼세부 튜토리얼: API 없이 GitHub 리포지토리 폴더 크롤링

Detailed Tutorial: Crawling GitHub Repository Folders Without API

매우 상세한 튜토리얼: API 없이 GitHub 리포지토리 폴더 크롤링

Shpetim Haxhiu가 작성한 이 매우 상세한 튜토리얼은 GitHub API에 의존하지 않고 프로그래밍 방식으로 GitHub 저장소 폴더를 크롤링하는 과정을 안내합니다. 여기에는 구조 이해부터 향상된 기능을 갖춘 강력하고 재귀적인 구현 제공에 이르기까지 모든 것이 포함됩니다.


1. 설정 및 설치

시작하기 전에 다음 사항을 확인하세요.

  1. Python: 버전 3.7 이상이 설치되어 있습니다.
  2. 라이브러리: 설치 요청 및 BeautifulSoup.
   pip install requests beautifulsoup4
  1. 편집기: VS Code 또는 PyCharm과 같은 Python 지원 IDE

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)
</folder></branch></repo></owner>

4. 기능 설명

  1. 요청 헤더: 사용자 에이전트 문자열을 사용하여 브라우저를 모방하고 차단을 방지합니다.
  2. 재귀 크롤링:
    • 폴더(/tree/)를 감지하여 재귀적으로 입력합니다.
    • 추가 입력 없이 파일(/blob/)을 나열합니다.
  3. 들여쓰기: 출력에 폴더 계층 구조를 반영합니다.
  4. 깊이 제한: 최대 깊이(max_length)를 설정하여 과도한 재귀를 방지합니다.

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)
</folder></branch></repo></owner>

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")
</folder></branch></repo></owner>

이 세부 가이드를 따르면 강력한 GitHub 폴더 크롤러를 구축할 수 있습니다. 이 도구는 윤리적 준수를 보장하면서 다양한 요구 사항에 맞게 조정할 수 있습니다.


댓글 섹션에 질문을 남겨주세요! 또한, 저에게 연락하는 것을 잊지 마세요:

  • 이메일: shpetim.h@gmail.com
  • LinkedIn: linkedin.com/in/shpetimhaxhiu
  • GitHub: github.com/shpetimhaxhiu

위 내용은 세부 튜토리얼: API 없이 GitHub 리포지토리 폴더 크롤링의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬 : 컴파일러 또는 통역사?파이썬 : 컴파일러 또는 통역사?May 13, 2025 am 12:10 AM

Python은 해석 된 언어이지만 편집 프로세스도 포함됩니다. 1) 파이썬 코드는 먼저 바이트 코드로 컴파일됩니다. 2) 바이트 코드는 Python Virtual Machine에 의해 해석되고 실행됩니다. 3)이 하이브리드 메커니즘은 파이썬이 유연하고 효율적이지만 완전히 편집 된 언어만큼 빠르지는 않습니다.

루프 대 루프를위한 파이썬 : 루프시기는 언제 사용해야합니까?루프 대 루프를위한 파이썬 : 루프시기는 언제 사용해야합니까?May 13, 2025 am 12:07 AM

USEAFORLOOPHENTERATINGOVERASERASERASPECIFICNUMBEROFTIMES; USEAWHILLOOPWHENTINUTIMONDITINISMET.FORLOOPSAREIDEALFORKNOWNSEDINGENCENCENS, WHILEWHILELOOPSSUITSITUATIONS WITHERMINGEDERITERATIONS.

파이썬 루프 : 가장 일반적인 오류파이썬 루프 : 가장 일반적인 오류May 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrors likeinfiniteloops, modifyinglistsdizeration, off-by-by-byerrors, zero-indexingissues, andnestedloopineficiencies.toavoidthese : 1) aing'i

파이썬의 루프 및 루프의 경우 : 각각의 장점은 무엇입니까?파이썬의 루프 및 루프의 경우 : 각각의 장점은 무엇입니까?May 13, 2025 am 12:01 AM

ForloopSareadvantageForkNowniTerations 및 Sequence, OffingSimplicityAndInamicConditionSandunkNowniTitionS 및 ControlOver Terminations를 제공합니다

파이썬 : 편집과 해석에 대한 깊은 다이빙파이썬 : 편집과 해석에 대한 깊은 다이빙May 12, 2025 am 12:14 AM

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?May 12, 2025 am 12:09 AM

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

루프 대 파이썬의 루프 : 주요 차이점 설명루프 대 파이썬의 루프 : 주요 차이점 설명May 12, 2025 am 12:08 AM

forloopsareideal when

루프를위한 것 및 기간 : 실용 가이드루프를위한 것 및 기간 : 실용 가이드May 12, 2025 am 12:07 AM

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구