1. 程式人生 > >用python爬蟲爬取和登陸github

用python爬蟲爬取和登陸github

一 利用API簡單爬取

利用GitHub提供的API爬取前十個star數量最多的Python庫

GitHub提供了很多專門為爬蟲準備的API介面,通過介面可以爬取到便捷,易處理的資訊。(這是GitHub官網的各種api介紹

    使用到的庫

import requests

    通過get請求到網頁的資訊

response = requests.get('https://api.github.com/search/repositories?q=language:python&sort=stars')
#檢測是否請求成功,若成功,狀態碼應該是200
if(response.status_code != 200):
    print('error: fail to request')

若我們自己點入上方的連結,會發現一個特別的網頁,沒有介面,只有由簡單的字元組成。

    仔細觀察,會發現字元和字典的結構是相同的,最上層是三個關鍵詞,其中 'items'關鍵詞儲存有一個List,裡面有多組字典資訊,每一個字典儲存有一個python庫的詳細資訊。

    所以直接提取相應資訊即可

#獲取的是一個json格式的字典物件
j = response.json()
#'items'下包括了前三十個庫的所有詳細資訊
items= j['items']

#儲存前十個資料
message = []
for i in range(10):
    pro = items[i]
    message.append(pro['full_name'])#庫的'作者/名字'
    #依次列印
    print('top%d:' % (i+1), pro['name'])#列印庫的名字

     列印結果:

top1: awesome-python
top2: system-design-primer
top3: models
top4: public-apis
top5: youtube-dl
top6: flask
top7: thefuck
top8: httpie
top9: django
top10: awesome-machine-learning