豆瓣電影top250爬蟲系列(一)--- 模擬登陸+爬取電影信息

github源碼下載

  • 首先聲明一點,由于豆瓣的api有訪問次數限制,應該是一分鐘內只允許40次請求,所以需要設置延時。
  • 超出限制后,豆瓣會反爬蟲,繼續請求ip檢測會出現異常,所以需要模擬登陸。
  • 我這里模擬登錄信息用的是最簡單的,我們在網頁登錄后獲取cookies信息,以保持登錄狀態:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
cookies = {'cookie': 'bid=lYQOsRcej_8; __guid=236236167.1056829666077886000.1525765977089.4163; __yadk_uid=oTZbiJ2I8VYoUXCoZzHcWoBroPcym2QB; gr_user_id=24156fa6-1963-48f2-8b87-6a021d165bde; viewed="26708119_24294210_24375031"; ps=y; __utmt=1; _vwo_uuid_v2=DE96132378BF4399896F28BD0E9CFC4FD|8f3c433c345d866ad9849be60f1fb2a0; ue="2287093698@qq.com"; _pk_ref.100001.8cb4=%5B%22%22%2C%22%22%2C1527272795%2C%22https%3A%2F%2Faccounts.douban.com%2Fsafety%2Funlock_sms%2Fresetpassword%3Fconfirmation%3Dbf9474e931a2fa9a%26alias%3D%22%5D; _ga=GA1.2.262335411.1525765981; _gid=GA1.2.856273377.1527272802; dbcl2="62325063:TQjdVXw2PtM"; ck=csZ5; monitor_count=11; _pk_id.100001.8cb4=7b30f754efe8428f.1525765980.15.1527272803.1527269181.; _pk_ses.100001.8cb4=*; push_noty_num=0; push_doumail_num=0; __utma=30149280.262335411.1525765981.1527266658.1527269182.62; __utmb=30149280.9.10.1527269182; __utmc=30149280; __utmz=30149280.1527266658.61.22.utmcsr=accounts.douban.com|utmccn=(referral)|utmcmd=referral|utmcct=/login; __utmv=30149280.6232; ap=1; ll="108289"'}
#連接請求URL,請求的是登錄以后的頁面
res = requests.get('https://movie.douban.com/top250?start='+ start, headers = headers, cookies = cookies)
#獲取相應文本,也就是對應html頁面的文本信息
html = res.text
print(html)
  • 獲取電影列表信息
def getMovieList(start):
    res = requests.get('https://movie.douban.com/top250?start='+ start, headers = headers, cookies = cookies)
    html = res.text

    # print(html)
    reg = r'<div class="item">.*?<a href="(.*?)">.*?<span class="title">(.*?)</span>.*?<p class="">(.*?)&nbsp.*?<br>.*?(.*?)&nbsp;/&nbsp;(.*?)&nbsp;/&nbsp;(.*?)</p>'
    reg += r'.*?<div class="star">.*?property="v:average">(.*?)</span>.*?<span>(.*?)</span>'
    reg += r'.*?<span class="inq">(.*?)</span>'

    return re.findall(reg, html, re.S)
  • 在列表頁獲取到對應電影的url,然后進入具體電影頁面,爬取相關信息。
def getMovieContent(url,movieId):
    res = requests.get(url, headers = headers, cookies = cookies)
    html = res.text

    # print(html)
    #匹配電影的所有演員信息
    reg = r'<span class="actor">(.*?)<br/>'
    actors = re.findall(reg, html)
   
    #存在電影獲獎信息爬取,否則空串匹配
    if '<div class="hd">' in html:
        prize = '<div class="hd">(.*?)'
    else:
        prize = ''

    #存在別名則爬取,否則空串匹配
    if "又名:" in html:
        alias = '</span> (.*?)<br/>'
    else:
        alias = ''

    #爬取電影的海報鏈接、上映日期、時長、別名、摘要、短評鏈接等等
    reg = r'<a class="nbgnbg".*?<img src="(.*?)".*?'
    reg += r'.*?<span property="v:initialReleaseDate" content="(.*?)".*?<span property="v:runtime" content="(.*?)">.*?'+alias
    reg += r'.*?<span property="v:summary".*?>(.*?)</span>.*?'+ prize +'<div id="recommendations" class="">'
    reg += r'.*?<a class="comment_btn j a_collect_btn".*?<a href="(.*?)">'

    if prize != '':
        if alias != '':
            poster, time, movieLength, otherName, summary, award, commentLink = re.findall(reg, html, re.S)[0]
        else:
            poster, time, movieLength, summary, award, commentLink = re.findall(reg, html, re.S)[0]
            otherName = ""
        reg = r'<li>.*?<a href=".*?">(.*?)</a>.*?<li>(.*?)</li>'
        for awardName, awardType in re.findall(reg, award, re.S):
            cursor.execute("insert into award(movieId, name, type) values('{}', '{}', '{}')".format(
                movieId, (""+awardName).replace("'", r"\'"), (""+awardType).replace("'", r"\'")))
    else:
        resultList = re.findall(reg, html, re.S)
        if len(resultList) != 0:
            if alias != '':
                poster, time, movieLength, otherName, summary, commentLink =  resultList[0]
            else:
                poster, time, movieLength, summary, commentLink = resultList[0]
                otherName = ""
        else:
            return

    # print(poster, actors, time, movieLength, otherName, summary, award, commentLink)
    if len(otherName) != 0:
        updateSql = "update movie set poster='{}', time='{}', movieLength='{}',otherName='{}', summary='{}', commentLink='{}' where id = '{}'".format(
            poster, (""+time).strip("\n").strip(), movieLength, (""+otherName).replace("'", r"\'"),(""+summary).strip().replace("'", r"\'"),
            (""+commentLink).replace("'", r"\'"), movieId)
    else:
        updateSql = "update movie set poster='{}', time='{}', movieLength='{}', summary='{}', commentLink='{}' where id = '{}'".format(
            poster, ("" + time).strip("\n").strip(), movieLength,
            ("" + summary).strip().replace("'", r"\'"), ("" + commentLink).replace("'", r"\'"), movieId
        )
    #更新電影信息
    cursor.execute(updateSql)

    # print(award)
    #存儲電影的所有演員信息,還有她的介紹頁面URL
    reg = r'<a href="(.*?)" rel="v:starring">(.*?)</a>'
    for link, name in re.findall(reg, str(actors)):
        cursor.execute("insert into actor(movieId, link, name) values('{}', '{}', '{}')".format(
            movieId, (""+link).replace("'", r"\'"), (str(name))))
    #存儲該電影短評論信息,以及評論人名稱,評論日期
    for userName, time, commentContent in getComment(commentLink):
        cursor.execute("insert into comment(movieId, userName, content, time) values('{}', '{}', '{}', '{}')".format(
            movieId, (""+userName).replace("'", r"\'"), (""+commentContent).replace("'", r"\'"), (""+time).strip("\n").strip()))

    conn.commit()
  • 爬取短評論頁面函數
def getComment(url):
    res = requests.get(""+url, headers = headers, cookies = cookies)
    html = res.text
    #三個參數:評論人、評論日期、評論內容
    reg = r'<span class="comment-info">.*?class="">(.*?)</a>.*?<span class="comment-time.*?>(.*?)</span>'
    reg += r'.*?<p class="">(.*?)</p>'

    return re.findall(reg, html, re.S)
  • 主函數
def startUpMovie():
    count = 0
    #一共250部,每頁25部,分十次爬取
    for i in range(0,10):
        for link, title, director, age, country, type, score, evaluationNum, note in getMovieList(str(25*i)):
            print('正在存儲----{}'.format(""+title))
            # print(link, title, director, age, country, type, score, evaluationNum, note)
            cursor.execute("insert into movie(link, title, director, age, country, type, score, evaluationNum, note)"
                           " values('{}', '{}','{}', '{}', '{}', '{}','{}', '{}', '{}')".format(
                            link, (""+title), (""+director[6:]).strip("導演: ").strip().replace("'", r"\'"), (""+age).strip("\n").strip(),
                             country, (""+type).strip("\n").strip().replace("'", r"\'"), score, evaluationNum[0:-3], note)
                           )


            getMovieContent(link, cursor.lastrowid)
            conn.commit()
            count += 1
            #每爬取兩部電影,休眠7秒,以防止ip被禁!
            if count % 2 == 0:
                time.sleep(7)
            print("num:'{}'".format(count))

#啟動爬蟲函數
startUpMovie()
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,119評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,382評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,038評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,853評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,616評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,112評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,192評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,355評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,869評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,727評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,928評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,467評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,165評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,570評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,813評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,585評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,892評論 2 372

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,618評論 25 708
  • 1.a attempt at:一個嘗試 2.hallmark:特點 One hallmark of a good ...
    小雨紛飛沁人心閱讀 377評論 0 0
  • 記得我上一年級的時候,我的肚子特別的疼。到了夜里,雞狗安靜不再叫的時候。我實在忍不住了,叫醒了正在提心吊膽的媽...
    吳志文童鞋閱讀 320評論 0 0
  • 80天,英國紳士可以乘熱氣球環游世界; 100天,一座遠大的獨立大廈可以拔地而起; 180天,人生的150分之一,...
    葫蘆哥Gourd閱讀 680評論 8 5
  • 其實真的是想唱歌給你聽的,可惜你把秘密刪了
    棲惶閱讀 178評論 0 0