一個(gè)爬取中國(guó)大學(xué)MOOC的爬蟲(chóng)

不知道什么時(shí)候?qū)懙牧艘抖眩l(fā)上來(lái)備份一下吧青柄。

# -*- coding: utf-8 -*-
'''A simple spider fetching data from the url http://www.icourse163.org/search.htm.

@author: uchkks
@file: Spider.py
@time: 2020-2-27 23:47

'''
import requests
import urllib.parse
import json
import time
from typing import Union, Optional, Tuple

__all__ = [
    "urlencode",
    "urldecode",
    "CourseItem",
    "spider_page_by_index",
    "spider_all"
]

urlencode = urllib.parse.quote
urldecode = urllib.parse.unquote
UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"


class CourseItem():
    """The item fetched in the website. Properties are the following:

    ``title``: The title of this course.
    ``photourl``: The url of this course photo.
    ``intro``: The introduction of this course.
    ``number``: The number of the students attending this course.
    ``courseurl``: The url of this course.

    """

    def __init__(self, title: str, photourl: str, intro: str, number: int, courseurl: str):
        self.title = title
        self.photourl = photourl
        self.intro = intro
        self.number = number
        self.courseurl = courseurl

    def __str__(self):
        return json.dumps(self.__dict__)

    def __repr__(self):
        return json.dumps(self.__dict__)


def newCourseItem(info: dict) -> Tuple[str, CourseItem]:
    """Create an instacne of CourseItem using the given ``info``(a ``dict``).

    Returns:
        A ``(str, CourseItem)`` will be returned. The first item is the ``courseid``
        (A format string, ``'{schoolid}-{courseid}'``), the second item is ``CourseItem.``
    """
    courseID = f'{info["schoolPanel"]["shortName"]}-{info["id"]}'
    title = info["name"]
    photourl = info["termPanel"]["bigPhotoUrl"]
    intro = info["termPanel"]["jsonContent"]
    number = info["termPanel"]["enrollCount"]
    courseurl = 'https://www.icourse163.org/course/' + courseID
    return courseID, CourseItem(title, photourl, intro, number, courseurl)


def spider_page_by_index(keyword: Union[str, bytes, bytearray],
                         pageindex: int = 1,
                         session: Optional[requests.Session] = None) -> dict:
    """Fetches data from the url www.icourse163.org/search.htm, using
    the given ``keyword`` and ``pageindex`` (optional) and returns a dict of result.

    Args:
        ``keyword``: must be a ``str``, ``bytes`` or ``bytearray`` instance, the keyword
        you want to lookup in the website.
        ``pageindex``: optional, an int, the current index of the page, default 1.
        ``session``: optional, an instance of requests.Session, if it is not provieded,
        a new session will be created.

    Returns:
        A ``dict`` containing search result will be returned.

    Raises:
        ``UnicodeError``: if keyword is a str and startwith the UTF-8 BOM '\ufeff', or
        the decode function cannot decode the bytes or bytearray correctly.
        ``TypeError``: if keyword is not an instance of str, bytes or bytearray, or
        pageindex is not an integer.
        ``RequestException``: an exception from module requests.exception, raises when
        an exception occurrs while handling a request.
    """
    if isinstance(keyword, str):
        if keyword.startswith('\ufeff'):
            raise UnicodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)")
    else:
        if not isinstance(keyword, (bytes, bytearray)):
            raise TypeError(f'the keyword must be str, bytes or bytearray, '
                            f'not {keyword.__class__.__name__}')
        if not isinstance(pageindex, int):
            raise TypeError(f'the pageindex must be int, '
                            f'not {keyword.__class__.__name__}')
        keyword = keyword.decode()
    url = f"http://www.icourse163.org/search.htm?search={urlencode(keyword)}#/"
    if session == None:
        session = requests.Session()
        session.get(url=url, headers={"User-Agent": UserAgent})
    csrfKey = session.cookies["NTESSTUDYSI"]
    postbody = f'query={{"keyword":"{keyword}","pageIndex":{pageindex}' \
               ',"highlight":true,"orderBy":0,"stats":30,"pageSize":20}'
    headers = session.headers
    headers["edu-script-token"] = csrfKey
    headers["Host"] = "www.icourse163.org"
    headers["Origin"] = "http://www.icourse163.org"
    headers["Referer"] = url
    headers["Content-Type"] = "application/x-www-form-urlencoded"
    res = session.post("https://www.icourse163.org/web/j/mocSearchBean.searchMocCourse.rpc"
                       f"?csrfKey={csrfKey}", data=postbody.encode(), headers=headers)
    text = res.text
    resultmap = json.loads(text)
    return resultmap


def spider_all(keyword: Union[str, bytes, bytearray]) -> dict:
    """Fetches data from the url www.icourse163.org/search.htm, using
    the given ``keyword`` and returns a dict of result.

    Args:
        ``keyword``: must be a ``str``, ``bytes`` or ``bytearray`` instance, the keyword
        you want to lookup in the website.

    Returns:
        A ``dict`` containing search result will be returned.

    Raises:
        ``UnicodeError``: if keyword is a str and startwith the UTF-8 BOM '\ufeff', or
        the decode function cannot decode the bytes or bytearray.
        ``TypeError``: if keyword is not an instance of str, bytes or bytearray.
        ``ValueError``: if fetching fails.
        ``RequestException``: an exception from module requests.exception, raises when
        an exception occurrs while handling a request.
    """
    session = requests.Session()
    url = f"http://www.icourse163.org/search.htm?search={urlencode(keyword)}#/"
    session.get(url=url, headers={"User-Agent": UserAgent})
    resultmap = spider_page_by_index(keyword, session=session)
    if resultmap["result"] == None:
        raise ValueError(f"The result map is not valid. The error message is {resultmap['message']}")
    resultmap = resultmap["result"]
    totlePageCount = resultmap["pagination"]["totlePageCount"] + 1
    result = {}
    for info in resultmap["result"]:
        courseID, course = newCourseItem(info["mocCourseCardDto"])
        result[courseID] = course
    for pageindex in range(2, totlePageCount):
        time.sleep(1)
        resultmap = spider_page_by_index(keyword, pageindex=pageindex, session=session)
        if resultmap["result"] == None:
            raise ValueError(f"The result map is not valid. The error message is {resultmap['message']}")
        resultmap = resultmap["result"]
        for info in resultmap["result"]:
            courseID, course = newCourseItem(info["mocCourseCardDto"])
            result[courseID] = course
    # print(result)
    return result


if __name__ == "__main__":
    print(spider_all("Python"))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蜂嗽,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子令境,更是在濱河造成了極大的恐慌晒旅,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,042評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件掷邦,死亡現(xiàn)場(chǎng)離奇詭異白胀,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)抚岗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,996評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門或杠,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人宣蔚,你說(shuō)我怎么就攤上這事向抢。” “怎么了胚委?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,674評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵挟鸠,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我亩冬,道長(zhǎng)艘希,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,340評(píng)論 1 283
  • 正文 為了忘掉前任硅急,我火速辦了婚禮覆享,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘营袜。我一直安慰自己撒顿,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,404評(píng)論 5 384
  • 文/花漫 我一把揭開(kāi)白布荚板。 她就那樣靜靜地躺著核蘸,像睡著了一般巍糯。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上客扎,一...
    開(kāi)封第一講書(shū)人閱讀 49,749評(píng)論 1 289
  • 那天祟峦,我揣著相機(jī)與錄音,去河邊找鬼徙鱼。 笑死宅楞,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的袱吆。 我是一名探鬼主播厌衙,決...
    沈念sama閱讀 38,902評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼绞绒!你這毒婦竟也來(lái)了婶希?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,662評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤蓬衡,失蹤者是張志新(化名)和其女友劉穎喻杈,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體狰晚,經(jīng)...
    沈念sama閱讀 44,110評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡筒饰,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了壁晒。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瓷们。...
    茶點(diǎn)故事閱讀 38,577評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖秒咐,靈堂內(nèi)的尸體忽然破棺而出谬晕,到底是詐尸還是另有隱情,我是刑警寧澤携取,帶...
    沈念sama閱讀 34,258評(píng)論 4 328
  • 正文 年R本政府宣布固蚤,位于F島的核電站,受9級(jí)特大地震影響歹茶,放射性物質(zhì)發(fā)生泄漏夕玩。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,848評(píng)論 3 312
  • 文/蒙蒙 一惊豺、第九天 我趴在偏房一處隱蔽的房頂上張望燎孟。 院中可真熱鬧,春花似錦尸昧、人聲如沸揩页。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,726評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)爆侣。三九已至萍程,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間兔仰,已是汗流浹背茫负。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,952評(píng)論 1 264
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留乎赴,地道東北人忍法。 一個(gè)月前我還...
    沈念sama閱讀 46,271評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像榕吼,于是被迫代替她去往敵國(guó)和親饿序。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,452評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容