Làm cách nào để trích xuất dữ liệu từ GitHub bằng Python?

GitHub là dịch vụ lưu trữ kho lưu trữ Git bổ sung nhiều tính năng riêng, chẳng hạn như giao diện đồ họa dựa trên web để quản lý kho lưu trữ, kiểm soát truy cập và một số tính năng khác, chẳng hạn như wiki, tổ chức, ý chính, v.v.

Như bạn có thể đã biết, có rất nhiều dữ liệu cần được lấy. Ngoài việc sử dụng API GitHub v3 bằng Python, bạn cũng có thể quan tâm đến việc tìm hiểu cách sử dụng API Google Drive bằng Python để tự động hóa các tác vụ liên quan đến Google Drive. Hoặc có lẽ bạn cần sử dụng API Gmail trong Python để tự động hóa các tác vụ liên quan đến tài khoản Gmail của mình

Trong hướng dẫn này, bạn sẽ tìm hiểu cách bạn có thể sử dụng GitHub API v3 trong Python bằng cách sử dụng cả yêu cầu hoặc thư viện PyGithub

Mục lục

Để bắt đầu, hãy cài đặt các phụ thuộc

$ pip3 install PyGithub requests

Có liên quan. Cách trích xuất dữ liệu YouTube bằng API YouTube trong Python

Lấy dữ liệu người dùng

Vì việc sử dụng Github API v3 khá đơn giản, bạn có thể thực hiện một yêu cầu

import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"//api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get[url].json[]
# pretty print JSON data
pprint[user_data]
3 đơn giản tới một URL cụ thể và truy xuất kết quả

import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"//api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get[url].json[]
# pretty print JSON data
pprint[user_data]

Ở đây tôi đã sử dụng tài khoản của mình;

{'avatar_url': '//avatars3.githubusercontent.com/u/37851086?v=4',
 'bio': None,
 'blog': '//www.thepythoncode.com',
 'company': None,
 'created_at': '2018-03-27T21:49:04Z',
 'email': None,
 'events_url': '//api.github.com/users/x4nth055/events{/privacy}',
 'followers': 93,
 'followers_url': '//api.github.com/users/x4nth055/followers',
 'following': 41,
 'following_url': '//api.github.com/users/x4nth055/following{/other_user}',
 'gists_url': '//api.github.com/users/x4nth055/gists{/gist_id}',
 'gravatar_id': '',
 'hireable': True,
 'html_url': '//github.com/x4nth055',
 'id': 37851086,
 'login': 'x4nth055',
 'name': 'Rockikz',

Rất nhiều dữ liệu, đó là lý do tại sao chỉ sử dụng thư viện yêu cầu sẽ không thuận tiện để trích xuất hàng tấn dữ liệu này theo cách thủ công. Do đó, PyGithub đã ra tay giải cứu

Có liên quan. Webhook trong Python với Flask

Nhận kho lưu trữ của người dùng

Hãy lấy tất cả các kho lưu trữ công khai của người dùng đó bằng thư viện PyGithub mà chúng ta vừa cài đặt

import base64
from github import Github
from pprint import pprint

# Github username
username = "x4nth055"
# pygithub object
g = Github[]
# get that user by username
user = g.get_user[username]

for repo in user.get_repos[]:
    print[repo]

Đây là đầu ra của tôi

Repository[full_name="x4nth055/aind2-rnn"]
Repository[full_name="x4nth055/awesome-algeria"]
Repository[full_name="x4nth055/emotion-recognition-using-speech"]
Repository[full_name="x4nth055/emotion-recognition-using-text"]
Repository[full_name="x4nth055/food-reviews-sentiment-analysis"]
Repository[full_name="x4nth055/hrk"]
Repository[full_name="x4nth055/lp_simplex"]
Repository[full_name="x4nth055/price-prediction"]
Repository[full_name="x4nth055/product_recommendation"]
Repository[full_name="x4nth055/pythoncode-tutorials"]
Repository[full_name="x4nth055/sentiment_analysis_naive_bayes"]

Được rồi, vì vậy tôi đã tạo một chức năng đơn giản để trích xuất một số thông tin hữu ích từ đối tượng Kho lưu trữ này

def print_repo[repo]:
    # repository full name
    print["Full name:", repo.full_name]
    # repository description
    print["Description:", repo.description]
    # the date of when the repo was created
    print["Date created:", repo.created_at]
    # the date of the last git push
    print["Date of last push:", repo.pushed_at]
    # home website [if available]
    print["Home Page:", repo.homepage]
    # programming language
    print["Language:", repo.language]
    # number of forks
    print["Number of forks:", repo.forks]
    # number of stars
    print["Number of stars:", repo.stargazers_count]
    print["-"*50]
    # repository content [files & directories]
    print["Contents:"]
    for content in repo.get_contents[""]:
        print[content]
    try:
        # repo license
        print["License:", base64.b64decode[repo.get_license[].content.encode[]].decode[]]
    except:
        pass

Đối tượng kho lưu trữ có rất nhiều lĩnh vực khác. Tôi đề nghị bạn sử dụng

import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"//api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get[url].json[]
# pretty print JSON data
pprint[user_data]
4 để lấy các trường bạn muốn in. Hãy lặp lại các kho lưu trữ một lần nữa và sử dụng chức năng chúng ta vừa viết

________số 8_______

Điều này sẽ in một số thông tin về từng kho lưu trữ công khai của người dùng này

====================================================================================================
Full name: x4nth055/pythoncode-tutorials
Description: The Python Code Tutorials
Date created: 2019-07-29 12:35:40
Date of last push: 2020-04-02 15:12:38
Home Page: //www.thepythoncode.com
Language: Python
Number of forks: 154
Number of stars: 150
--------------------------------------------------
Contents:
ContentFile[path="LICENSE"]
ContentFile[path="README.md"]
ContentFile[path="ethical-hacking"]
ContentFile[path="general"]
ContentFile[path="images"]
ContentFile[path="machine-learning"]
ContentFile[path="python-standard-library"]
ContentFile[path="scapy"]
ContentFile[path="web-scraping"]
License: MIT License

Tôi đã cắt bớt toàn bộ đầu ra, vì nó sẽ trả về tất cả các kho lưu trữ và thông tin của chúng; . get_contents[""] để truy xuất tất cả các tệp và thư mục của kho lưu trữ đó, PyGithub phân tích nó thành một đối tượng ContentFile, sử dụng

import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"//api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get[url].json[]
# pretty print JSON data
pprint[user_data]
5 để xem các trường hữu ích khác

Trích xuất kho lưu trữ riêng của người dùng đã đăng nhập

Ngoài ra, nếu bạn có kho lưu trữ riêng, bạn có thể truy cập chúng bằng cách xác thực tài khoản của mình [sử dụng thông tin đăng nhập chính xác] bằng PyGithub như sau

username = "username"
password = "password"

# authenticate to github
g = Github[username, password]
# get the authenticated user
user = g.get_user[]
for repo in user.get_repos[]:
    print_repo[repo]

GitHub cũng đề xuất sử dụng các yêu cầu đã xác thực vì nó sẽ tăng RateLimitExceededException nếu bạn sử dụng yêu cầu công khai [không có xác thực] và vượt quá một số lượng nhỏ yêu cầu

Tải xuống tệp trong kho lưu trữ

Bạn cũng có thể tải xuống bất kỳ tệp nào từ bất kỳ kho lưu trữ nào bạn muốn. Để làm điều đó, tôi đang chỉnh sửa hàm

import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"//api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get[url].json[]
# pretty print JSON data
pprint[user_data]
6 để tìm kiếm các tệp Python trong một kho lưu trữ nhất định. Nếu tìm thấy, chúng tôi đặt tên tệp thích hợp và viết nội dung của nó bằng thuộc tính
import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"//api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get[url].json[]
# pretty print JSON data
pprint[user_data]
7. Đây là phiên bản đã chỉnh sửa của hàm
import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"//api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get[url].json[]
# pretty print JSON data
pprint[user_data]
6

# make a directory to save the Python files
if not os.path.exists["python-files"]:
    os.mkdir["python-files"]

def print_repo[repo]:
    # repository full name
    print["Full name:", repo.full_name]
    # repository description
    print["Description:", repo.description]
    # the date of when the repo was created
    print["Date created:", repo.created_at]
    # the date of the last git push
    print["Date of last push:", repo.pushed_at]
    # home website [if available]
    print["Home Page:", repo.homepage]
    # programming language
    print["Language:", repo.language]
    # number of forks
    print["Number of forks:", repo.forks]
    # number of stars
    print["Number of stars:", repo.stargazers_count]
    print["-"*50]
    # repository content [files & directories]
    print["Contents:"]
    try:
        for content in repo.get_contents[""]:
            # check if it's a Python file
            if content.path.endswith[".py"]:
                # save the file
                filename = os.path.join["python-files", f"{repo.full_name.replace['/', '-']}-{content.path}"]
                with open[filename, "wb"] as f:
                    f.write[content.decoded_content]
            print[content]
        # repo license
        print["License:", base64.b64decode[repo.get_license[].content.encode[]].decode[]]
    except Exception as e:
        print["Error:", e]

Sau khi bạn chạy lại mã [bạn có thể lấy mã hoàn chỉnh của toàn bộ hướng dẫn tại đây], bạn sẽ nhận thấy một thư mục có tên

import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"//api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get[url].json[]
# pretty print JSON data
pprint[user_data]
9 được tạo có chứa các tệp Python từ các kho lưu trữ khác nhau của người dùng đó

học cũng được. Cách tạo trình rút ngắn URL trong Python

Tìm kiếm kho lưu trữ

API GitHub khá phong phú;

import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"//api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get[url].json[]
# pretty print JSON data
pprint[user_data]
0

Điều này sẽ trả về 9 kho lưu trữ và thông tin của họ

Bạn cũng có thể tìm kiếm theo ngôn ngữ lập trình hoặc chủ đề

import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"//api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get[url].json[]
# pretty print JSON data
pprint[user_data]
1

Để tìm kiếm một chủ đề cụ thể, bạn chỉ cần đặt một cái gì đó như

{'avatar_url': '//avatars3.githubusercontent.com/u/37851086?v=4',
 'bio': None,
 'blog': '//www.thepythoncode.com',
 'company': None,
 'created_at': '2018-03-27T21:49:04Z',
 'email': None,
 'events_url': '//api.github.com/users/x4nth055/events{/privacy}',
 'followers': 93,
 'followers_url': '//api.github.com/users/x4nth055/followers',
 'following': 41,
 'following_url': '//api.github.com/users/x4nth055/following{/other_user}',
 'gists_url': '//api.github.com/users/x4nth055/gists{/gist_id}',
 'gravatar_id': '',
 'hireable': True,
 'html_url': '//github.com/x4nth055',
 'id': 37851086,
 'login': 'x4nth055',
 'name': 'Rockikz',
0 trong phương thức
{'avatar_url': '//avatars3.githubusercontent.com/u/37851086?v=4',
 'bio': None,
 'blog': '//www.thepythoncode.com',
 'company': None,
 'created_at': '2018-03-27T21:49:04Z',
 'email': None,
 'events_url': '//api.github.com/users/x4nth055/events{/privacy}',
 'followers': 93,
 'followers_url': '//api.github.com/users/x4nth055/followers',
 'following': 41,
 'following_url': '//api.github.com/users/x4nth055/following{/other_user}',
 'gists_url': '//api.github.com/users/x4nth055/gists{/gist_id}',
 'gravatar_id': '',
 'hireable': True,
 'html_url': '//github.com/x4nth055',
 'id': 37851086,
 'login': 'x4nth055',
 'name': 'Rockikz',
1

Đọc thêm. Cách trích xuất dữ liệu Wikipedia bằng Python

Thao tác tệp trong kho lưu trữ của bạn

Nếu bạn đang sử dụng phiên bản xác thực, bạn cũng có thể tạo, cập nhật và xóa tệp rất dễ dàng bằng API

import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"//api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get[url].json[]
# pretty print JSON data
pprint[user_data]
2

Đoạn mã trên là một trường hợp sử dụng đơn giản; . Sau đó, tôi lấy nội dung của tệp mới đó và xóa nó [và nó cũng sẽ được tính là

{'avatar_url': '//avatars3.githubusercontent.com/u/37851086?v=4',
 'bio': None,
 'blog': '//www.thepythoncode.com',
 'company': None,
 'created_at': '2018-03-27T21:49:04Z',
 'email': None,
 'events_url': '//api.github.com/users/x4nth055/events{/privacy}',
 'followers': 93,
 'followers_url': '//api.github.com/users/x4nth055/followers',
 'following': 41,
 'following_url': '//api.github.com/users/x4nth055/following{/other_user}',
 'gists_url': '//api.github.com/users/x4nth055/gists{/gist_id}',
 'gravatar_id': '',
 'hireable': True,
 'html_url': '//github.com/x4nth055',
 'id': 37851086,
 'login': 'x4nth055',
 'name': 'Rockikz',
3]

Và chắc chắn, sau khi thực thi các dòng mã trên, các xác nhận đã được tạo và đẩy

Phần kết luận

Chúng tôi vừa mới tìm hiểu sơ qua về API GitHub, còn rất nhiều chức năng và phương pháp khác mà bạn có thể sử dụng và rõ ràng là chúng tôi không thể đề cập đến tất cả chúng. Dưới đây là một số cách hữu ích mà bạn có thể tự kiểm tra

  • g. get_organization[đăng nhập]. Trả về một đối tượng Tổ chức đại diện cho một tổ chức GitHub
  • g. get_gist[id]. Trả về một đối tượng Gist đại diện cho một ý chính trong GitHub
  • g. search_code[truy vấn]. Trả về một danh sách được phân trang của các đối tượng ContentFile đại diện cho các tệp phù hợp trên một số kho lưu trữ
  • g. search_topics[truy vấn]. Trả về danh sách được phân trang của các đối tượng Chủ đề đại diện cho một chủ đề GitHub
  • g. search_commits[truy vấn]. Trả về danh sách các đối tượng Cam kết được phân trang trong đó nó đại diện cho một cam kết trong GitHub

Còn nhiều nữa; . Kiểm tra tài liệu PyGithub hoặc API GitHub để biết thông tin chi tiết

Làm cách nào để đọc dữ liệu trực tiếp từ GitHub bằng Python?

Phương pháp đầu tiên khá đơn giản. tất cả những gì bạn cần làm là đặt. tệp csv trong kho lưu trữ GitHub. Bây giờ, tất cả những gì bạn phải làm là nhập url của. tệp csv trong mã .

Bạn có thể trích xuất dữ liệu bằng Python không?

Một trong những tính năng quan trọng nhất của ScrapingBee là khả năng trích xuất dữ liệu chính xác mà không cần xử lý hậu kỳ nội dung của yêu cầu bằng thư viện bên ngoài . Chúng tôi có thể sử dụng tính năng này bằng cách chỉ định một tham số bổ sung có tên extract_rules.

Chủ Đề