python爬蟲——爬取大學排名資訊

阿布多abu發表於2019-08-02


2. 這次爬取的網址請搜尋“阿凡題”(純技術討論)

“阿凡題”(純技術討論

3. 在該網址選擇查院校,其他都是預設

4. 這次爬取的資訊主要是下圖紅框的內容,在瀏覽器開發者中,點選XHR就可以發現這個介面,介面的內容都有我們需要的資訊。



å¨è¿éæ入å¾çæè¿°

5. 先構建請求頭,請求頭直接複製過來了
在這裡插入圖片描述

# 構建請求頭

headers = {

    'Accept': '*/*',

    'Accept-Encoding': 'gzip, deflate',

    'Accept-Language': 'zh-CN,zh;q=0.9',

    'Connection': 'keep-alive',

    'contentType': 'application/x-www-form-urlencoded; charset=utf-8',

    'Cookie': 'cfm-major=true',

    'Host': 'gaokao.afanti100.com',

    'media': 'PC',

    'Referer': '

    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36',

    'X-Requested-With': 'XMLHttpRequest',

}

6. 接下來先請求這條url,透過format方法實現對url的拼接,以此達到翻頁的效果,透過檢視介面的內容,發現是json格式,大學的資訊在data鍵中的university_lst中,因此我們需要取出這個鍵,其中university_lst是列表。


å¨è¿éæ入å¾çæè¿°


def get_index():


    page = 1

    while True:

        if page > 188:

            break

        url = ' \

              '&university_type=0&location_province=0&speciality=0&page={}'.format(page)

        # page自增一實現翻頁

        page += 1

        # 請求url並返回的是json格式

        resp = requests.get(url, headers=headers).json()

        # 取出大學所在的鍵值對

        university_lsts = resp.get('data').get('university_lst')

        if university_lsts:

            get_info(university_lsts)

        else:

            continue

7. 透過上一步取出鍵值對之後,就可以遍歷列表取出我們想要的資訊。

def get_info(university_lsts):

    # 判斷列表是否不為空

    if university_lsts:

        # 遍歷列表取出每個大學的資訊

        for university_lst in university_lsts:

            # 宣告一個字典儲存資料

            data_dict = {}


            # 大學名字

            data_dict['name'] = university_lst.get('name')

            # 大學排名

            data_dict['ranking'] = university_lst.get('ranking')

            # 大學標籤

            data_dict['tag_lst'] = university_lst.get('tag_lst')

            # 大學重點學科

            data_dict['key_major_count'] = university_lst.get('key_major_count')

            # 碩士點數

            data_dict['graduate_program_count'] = university_lst.get('graduate_program_count')

            # 博士點數

            data_dict['doctoral_program_count'] = university_lst.get('doctoral_program_count')

            # 是否211

            data_dict['is_211'] = university_lst.get('is_211')

            # 是否985

            data_dict['is_985'] = university_lst.get('is_985')

            # 哪個省

            data_dict['location_province'] = university_lst.get('location_province')

            # 哪個城市

            data_dict['location_city'] = university_lst.get('location_city')

            # 大學型別

            data_dict['university_type'] = university_lst.get('university_type')


            data_list.append(data_dict)

            print(data_dict)

8. 最後將資訊儲存為檔案

 

def save_file():

    # 將資料儲存為json檔案

    with open('大學排名資訊.json', 'w', encoding='utf-8') as f:

        json.dump(data_list, f, ensure_ascii=False, indent=4)

    print('json檔案儲存成功')


    # 將資料儲存為csv檔案

    # 表頭

    title = data_list[0].keys()

    with open('大學排名資訊.csv', 'w', encoding='utf-8', newline='') as f:

        writer = csv.DictWriter(f, title)

        # 寫入表頭

        writer.writeheader()

        # 寫入資料

        writer.writerows(data_list)

    print('csv檔案儲存成功')

9. 這次爬蟲很簡單,新手可以用來練練手,全部程式碼附上

import requests

import json

import csv



# 構建請求頭

headers = {

    'Accept': '*/*',

    'Accept-Encoding': 'gzip, deflate',

    'Accept-Language': 'zh-CN,zh;q=0.9',

    'Connection': 'keep-alive',

    'contentType': 'application/x-www-form-urlencoded; charset=utf-8',

    'Cookie': 'cfm-major=true',

    'Host': 'gaokao.afanti100.com',

    'media': 'PC',

    'Referer': '

    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36',

    'X-Requested-With': 'XMLHttpRequest',

}



# 宣告一個列表儲存字典

data_list = []



def get_index():


    page = 1

    while True:

        if page > 188:

            break

        url = ' \

              '&university_type=0&location_province=0&speciality=0&page={}'.format(page)

        # page自增一實現翻頁

        page += 1

        # 請求url並返回的是json格式

        resp = requests.get(url, headers=headers).json()

        # 取出大學所在的鍵值對

        university_lsts = resp.get('data').get('university_lst')

        if university_lsts:

            get_info(university_lsts)

        else:

            continue



def get_info(university_lsts):

    # 判斷列表是否不為空

    if university_lsts:

        # 遍歷列表取出每個大學的資訊

        for university_lst in university_lsts:

            # 宣告一個字典儲存資料

            data_dict = {}


            # 大學名字

            data_dict['name'] = university_lst.get('name')

            # 大學排名

            data_dict['ranking'] = university_lst.get('ranking')

            # 大學標籤

            data_dict['tag_lst'] = university_lst.get('tag_lst')

            # 大學重點學科

            data_dict['key_major_count'] = university_lst.get('key_major_count')

            # 碩士點數

            data_dict['graduate_program_count'] = university_lst.get('graduate_program_count')

            # 博士點數

            data_dict['doctoral_program_count'] = university_lst.get('doctoral_program_count')

            # 是否211

            data_dict['is_211'] = university_lst.get('is_211')

            # 是否985

            data_dict['is_985'] = university_lst.get('is_985')

            # 哪個省

            data_dict['location_province'] = university_lst.get('location_province')

            # 哪個城市

            data_dict['location_city'] = university_lst.get('location_city')

            # 大學型別

            data_dict['university_type'] = university_lst.get('university_type')


            data_list.append(data_dict)

            print(data_dict)



def save_file():

    # 將資料儲存為json檔案

    with open('大學排名資訊.json', 'w', encoding='utf-8') as f:

        json.dump(data_list, f, ensure_ascii=False, indent=4)

    print('json檔案儲存成功')


    # 將資料儲存為csv檔案

    # 表頭

    title = data_list[0].keys()

    with open('大學排名資訊.csv', 'w', encoding='utf-8', newline='') as f:

        writer = csv.DictWriter(f, title)

        # 寫入表頭

        writer.writeheader()

        # 寫入資料

        writer.writerows(data_list)

    print('csv檔案儲存成功')



def main():

    get_index()

    save_file()



if __name__ == '__main__':

    main()







來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69903461/viewspace-2652619/,如需轉載,請註明出處,否則將追究法律責任。

相關文章