<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # 3.4 抓取貓眼電影排行 ## 實戰演練 利用 Requests 和正則表達式來抓取貓眼電影 TOP100 的相關內容 ## 1.目標 貓眼電影地址:[http://maoyan.com/board/4](http://maoyan.com/board/4) 需要:要提取出貓眼電影 TOP100 榜的電影名稱、時間、評分、圖片等信息,提取的結果我們以文件形式保存下來 ## 2.準備 確保[安裝requests庫](../../1kai-fa-huan-jing-pei-zhi/12-qing-qiu-ku-de-an-zhuang/121-requestsde-an-zhuang.md) ## 3.抓取分析 打開[http://maoyan.com/board/4可以查看榜單信息](http://maoyan.com/board/4可以查看榜單信息) ![](https://box.kancloud.cn/4b424abd17cd497ba84c43606b9c13d9_1920x1043.png) 在圖中可以清楚地看到影片的信息,頁面中顯示的信息有影片名稱、主演、上映時間、上映地區、評分、圖片等 之后點擊下一頁 ![](https://box.kancloud.cn/42cb21784ba03483bbe2752a9fa81177_1595x1008.png)可以發現[http://maoyan.com/board/4?offset=10比之前的url多了一個參數offset,參數值為10,目前顯示的排行數據11~20,可以判斷offset是一個偏移量的參數再點擊下一頁,發現頁面的](http://maoyan.com/board/4?offset=10比之前的url多了一個參數offset,參數值為10,目前顯示的排行數據11~20,可以判斷offset是一個偏移量的參數再點擊下一頁,發現頁面的) URL 變成了:[http://maoyan.com/board/4?offset=20](http://maoyan.com/board/4?offset=20),參數 offset 變成了 20,而顯示的結果是排行 21-30 的電影 可以判斷offset是一個偏移量,如果偏移值為n,則當前頁面的序號為n+1到n+10,這樣就可以更根據offset獲取top100的所有電影信息了 ## 4.抓取首頁 定義一個get\_first\_page\(\)函數方法,實現抓取首頁,代碼實現 ```text import requests import time headers = { 'Cookie': 'uuid_n_v=v1; uuid=AF3D1220948011E8B2AA9FA8B2681702285785F0A8C6440893B814F988D9E847; _csrf=7e74e8ba9e19ad80506d12f9c59ca4d0663c09568af4bd8ab119e7fa42cf0406; _lxsdk_cuid=164eec2d003c8-08f976660a5271-2711f38-144000-164eec2d003c8; _lxsdk=AF3D1220948011E8B2AA9FA8B2681702285785F0A8C6440893B814F988D9E847; __mta=210171562.1533014102076.1533015465347.1533015624851.12; _lxsdk_s=164eec2d004-581-309-f99%7C%7C29', 'Host': 'maoyan.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.15 Safari/537.36', } # 獲取首頁 def get_first_page(url): time.sleep(2) response = requests.get(url,headers=headers) if response.status_code == requests.codes.ok: return response.text return None # 主程序 def main(): url = "http://maoyan.com/board/4" html = get_first_page(url) print(html) if __name__ == "__main__": main() ``` tips:一定要加上請求頭,不然貓眼網站會禁止訪問 ## 5. 正則提取 {#5-正則提取} 現在抓取了首頁,需要進一步抓取相關信息,接下來回到網頁看一下頁面的真實源碼,在開發者工具中 Network 監聽,然后查看一下源代碼,注意這里不要在 Elements 選項卡直接查看源碼,此處的源碼可能經過 JavaScript 的操作而和原始請求的不同,需要從Network選項卡部分查看原始請求得到的源碼 ![](https://box.kancloud.cn/5cac13a606458112abcf40637cb748cb_1920x1046.png) 先看下一個電影的相關內容 ```text <dd> <i class="board-index board-index-1">1</i> <a href="/films/1203" title="霸王別姬" class="image-link" data-act="boarditem-click" data-val="{movieId:1203}"> <img src="//ms0.meituan.net/mywww/image/loading_2.e3d934bf.png" alt="" class="poster-default" /> <img data-src="http://p1.meituan.net/movie/20803f59291c47e1e116c11963ce019e68711.jpg@160w_220h_1e_1c" alt="霸王別姬" class="board-img" /> </a> <div class="board-item-main"> <div class="board-item-content"> <div class="movie-item-info"> <p class="name"><a href="/films/1203" title="霸王別姬" data-act="boarditem-click" data-val="{movieId:1203}">霸王別姬</a></p> <p class="star"> 主演:張國榮,張豐毅,鞏俐 </p> <p class="releasetime">上映時間:1993-01-01(中國香港)</p> </div> <div class="movie-item-number score-num"> <p class="score"><i class="integer">9.</i><i class="fraction">6</i></p> </div> </div> </div> </dd> ``` 現在需要從這段里面提取需要的信息,書寫正則表達式 ```text 排名信息:<i.*?board-index.*?>(.*?)</i>' 進一步編寫: 封面圖片:<i.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)" 繼續: 電影名稱<i.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?a.*?>(.*?)</a> 依次類推: 所有信息:<i.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd> ``` 這樣就可以提取第一頁的內容,代碼如下: ```text def parse_first_page(html): pattern = re.compile('<i.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>',re.S) items = re.findall(pattern,html) print(items) ``` 運行結果: ```text [('1', 'http://p1.meituan.net/movie/20803f59291c47e1e116c11963ce019e68711.jpg@160w_220h_1e_1c', '\n ', '\n 主演:張國榮,張豐毅,鞏俐\n ', '上映時間:1993-01-01(中國香港)', '9.', '6'), ('2', 'http://p0.meituan.net/movie/283292171619cdfd5b240c8fd093f1eb255670.jpg@160w_220h_1e_1c', '\n ', '\n 主演:蒂姆·羅賓斯,摩根·弗里曼,鮑勃·岡頓\n ', '上映時間:1994-10-14(美國)', '9.', '5'), ('3', 'http://p0.meituan.net/movie/54617769d96807e4d81804284ffe2a27239007.jpg@160w_220h_1e_1c', '\n ', '\n 主演:格利高里·派克,奧黛麗·赫本,埃迪·艾伯特\n ', '上映時間:1953-09-02(美國)', '9.', '1'), ('4', 'http://p0.meituan.net/movie/e55ec5d18ccc83ba7db68caae54f165f95924.jpg@160w_220h_1e_1c', '\n ', '\n 主演:讓·雷諾,加里·奧德曼,娜塔莉·波特曼\n ', '上映時間:1994-09-14(法國)', '9.', '5'), ('5', 'http://p1.meituan.net/movie/f5a924f362f050881f2b8f82e852747c118515.jpg@160w_220h_1e_1c', '\n ', '\n 主演:馬龍·白蘭度,阿爾·帕西諾,詹姆斯·肯恩\n ', '上映時間:1972-03-24(美國)', '9.', '3'), ('6', 'http://p1.meituan.net/movie/0699ac97c82cf01638aa5023562d6134351277.jpg@160w_220h_1e_1c', '\n ', '\n 主演:萊昂納多·迪卡普里奧,凱特·溫絲萊特,比利·贊恩\n ', '上映時間:1998-04-03', '9.', '5'), ('7', 'http://p0.meituan.net/movie/b03e9c52c585635d2cb6a3f7c08a8a50112441.jpg@160w_220h_1e_1c', '\n ', '\n 主演:日高法子,坂本千夏,糸井重里\n ', '上映時間:1988-04-16(日本)', '9.', '2'), ('8', 'http://p0.meituan.net/movie/da64660f82b98cdc1b8a3804e69609e041108.jpg@160w_220h_1e_1c', '\n ', '\n 主演:周星馳,鞏俐,鄭佩佩\n ', '上映時間:1993-07-01(中國香港)', '9.', '2'), ('9', 'http://p0.meituan.net/movie/b076ce63e9860ecf1ee9839badee5228329384.jpg@160w_220h_1e_1c', '\n ', '\n 主演:柊瑠美,入野自由,夏木真理\n ', '上映時間:2001-07-20(日本)', '9.', '3'), ('10', 'http://p0.meituan.net/movie/46c29a8b8d8424bdda7715e6fd779c66235684.jpg@160w_220h_1e_1c', '\n ', '\n 主演:費雯·麗,羅伯特·泰勒,露塞爾·沃特森\n ', '上映時間:1940-05-17(美國)', '9.', '2')] ``` 由于數據看起來比較雜亂,需要處理一下,遍歷生成為字典 改寫: ```text def parse_first_page(html): pattern = re.compile('<i.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>',re.S) items = re.findall(pattern,html) for item in items: # 利用迭代生成器 yield { 'index':item[0], 'image':item[1], 'title':item[2].strip(), 'actor':item[3].strip()[3:] if len(item[3]) > 3 else '', 'time':item[4].strip()[5:] if len(item[4]) > 5 else '', 'score':item[5].strip()+item[6].strip() } ``` 運行結果: ```text {'index': '1', 'image': 'http://p1.meituan.net/movie/20803f59291c47e1e116c11963ce019e68711.jpg@160w_220h_1e_1c', 'title': '', 'actor': '張國榮,張豐毅,鞏俐', 'time': '1993-01-01(中國香港)', 'score': '9.6'} {'index': '2', 'image': 'http://p0.meituan.net/movie/283292171619cdfd5b240c8fd093f1eb255670.jpg@160w_220h_1e_1c', 'title': '', 'actor': '蒂姆·羅賓斯,摩根·弗里曼,鮑勃·岡頓', 'time': '1994-10-14(美國)', 'score': '9.5'} {'index': '3', 'image': 'http://p0.meituan.net/movie/54617769d96807e4d81804284ffe2a27239007.jpg@160w_220h_1e_1c', 'title': '', 'actor': '格利高里·派克,奧黛麗·赫本,埃迪·艾伯特', 'time': '1953-09-02(美國)', 'score': '9.1'} {'index': '4', 'image': 'http://p0.meituan.net/movie/e55ec5d18ccc83ba7db68caae54f165f95924.jpg@160w_220h_1e_1c', 'title': '', 'actor': '讓·雷諾,加里·奧德曼,娜塔莉·波特曼', 'time': '1994-09-14(法國)', 'score': '9.5'} {'index': '5', 'image': 'http://p1.meituan.net/movie/f5a924f362f050881f2b8f82e852747c118515.jpg@160w_220h_1e_1c', 'title': '', 'actor': '馬龍·白蘭度,阿爾·帕西諾,詹姆斯·肯恩', 'time': '1972-03-24(美國)', 'score': '9.3'} {'index': '6', 'image': 'http://p1.meituan.net/movie/0699ac97c82cf01638aa5023562d6134351277.jpg@160w_220h_1e_1c', 'title': '', 'actor': '萊昂納多·迪卡普里奧,凱特·溫絲萊特,比利·贊恩', 'time': '1998-04-03', 'score': '9.5'} {'index': '7', 'image': 'http://p0.meituan.net/movie/b03e9c52c585635d2cb6a3f7c08a8a50112441.jpg@160w_220h_1e_1c', 'title': '', 'actor': '日高法子,坂本千夏,糸井重里', 'time': '1988-04-16(日本)', 'score': '9.2'} {'index': '8', 'image': 'http://p0.meituan.net/movie/da64660f82b98cdc1b8a3804e69609e041108.jpg@160w_220h_1e_1c', 'title': '', 'actor': '周星馳,鞏俐,鄭佩佩', 'time': '1993-07-01(中國香港)', 'score': '9.2'} {'index': '9', 'image': 'http://p0.meituan.net/movie/b076ce63e9860ecf1ee9839badee5228329384.jpg@160w_220h_1e_1c', 'title': '', 'actor': '柊瑠美,入野自由,夏木真理', 'time': '2001-07-20(日本)', 'score': '9.3'} {'index': '10', 'image': 'http://p0.meituan.net/movie/46c29a8b8d8424bdda7715e6fd779c66235684.jpg@160w_220h_1e_1c', 'title': '', 'actor': '費雯·麗,羅伯特·泰勒,露塞爾·沃特森', 'time': '1940-05-17(美國)', 'score': '9.2'} ``` ## 6. 寫入文件 {#6-寫入文件} 把數據存儲到文本文件中,在這里直接寫入到一個文本文件中,通過 json 庫的 dumps\(\) 方法實現字典的序列化,并指定 ensure\_ascii 參數為 False,這樣可以保證輸出的結果是中文形式而不是 Unicode 編碼 實例: ```text # 存儲數據 def save_to_json(content): with open('data.txt','a',encoding='utf-8') as f: # print(type(json.dumps(content))) f.write(json.dumps(content,ensure_ascii=False,)) # 主程序 def main(): url = "http://maoyan.com/board/4" html = get_first_page(url) for item in parse_first_page(html): save_to_json(item) ``` ## 7.完成代碼 ```text import requests import time import re import json count = 0 headers = { 'Cookie': 'uuid_n_v=v1; uuid=AF3D1220948011E8B2AA9FA8B2681702285785F0A8C6440893B814F988D9E847; _csrf=7e74e8ba9e19ad80506d12f9c59ca4d0663c09568af4bd8ab119e7fa42cf0406; _lxsdk_cuid=164eec2d003c8-08f976660a5271-2711f38-144000-164eec2d003c8; _lxsdk=AF3D1220948011E8B2AA9FA8B2681702285785F0A8C6440893B814F988D9E847; __mta=210171562.1533014102076.1533015465347.1533015624851.12; _lxsdk_s=164eec2d004-581-309-f99%7C%7C29', 'Host': 'maoyan.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.15 Safari/537.36', } # 獲取首頁 def get_page(url): time.sleep(2) response = requests.get(url,headers=headers) if response.status_code == requests.codes.ok: return response.text return None # 解析第一頁 def parse_page(html): pattern = re.compile('<i.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>',re.S) items = re.findall(pattern,html) for item in items: global count count = count + 1 yield { 'index':item[0], 'image':item[1], 'title':item[2].strip(), 'actor':item[3].strip()[3:] if len(item[3]) > 3 else '', 'time':item[4].strip()[5:] if len(item[4]) > 5 else '', 'score':item[5].strip()+item[6].strip() } # 存儲數據 def save_to_json(content): with open('data.txt','a',encoding='utf-8') as f: # print(type(json.dumps(content))) f.write(json.dumps(content,ensure_ascii=False,)) # 主程序 def main(offset): url = "http://maoyan.com/board/4?"+str(offset) html = get_page(url) for item in parse_page(html): save_to_json(item) if __name__ == "__main__": for i in range(10): offset = i*10 main(offset) time.sleep(1) print(count+"條數據") ``` 運行后可以在data.txt看到如下數據 ![](https://box.kancloud.cn/f325a5f4fe121bb8e4f49c5f5ad22e66_763x385.png) ## 8.代碼地址 貓眼爬蟲地址:[https://github.com/CoderAngle/Code\_practice\_project/tree/master/maoyan](https://github.com/CoderAngle/Code_practice_project/tree/master/maoyan)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看