1. 程式人生 > >Python爬蟲-爬取貓眼電影Top100榜單

Python爬蟲-爬取貓眼電影Top100榜單

貓眼電影的網站html組成十分簡單。
這裡寫圖片描述
地址就是很簡單的offset=x 這個x引數更改即可翻頁。
下面的資訊使用正則表示式很快就可以得出結果。
直接放程式碼:

import json
import re

import requests
from requests.exceptions import RequestException

#獲取一個url下的html檔案
def get_one_page(url):
    try:
        res = requests.get(url)
        if res.status_code == 200:
            print('請求成功'
) return res.text print('請求失敗') return None except RequestException: return None #解析html檔案 其中使用了正則匹配 def parse_one_page(html): #如果不加re.S(任意匹配) .就不會匹配換行符! pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)" alt="(.*?)" class="board-img" />.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>'
, re.S) items = re.findall(pattern, html) for item in items: #構造一個生成器可以使用 for遍歷 #生成一個字典 yield{ 'index' : item[0], 'image': item[1], 'title': item[2], #strip()去除空格和\n 切片去除 主演: 'actor': item[3].strip()[3:], 'time'
: item[4].strip()[5:], 'score' : item[5]+item[6] } #寫入檔案 使用json載入字典 def write_to_file(content): #加上encoding='utf-8' 和 ensure_ascii=False顯示漢字 with open('result.txt', 'a', encoding='utf-8') as f: #字典轉換成 字串 f.write(json.dumps(content, ensure_ascii=False) + '\n') f.close() #主函式執行 def main(): html = get_one_page('http://maoyan.com/board/4?') for item in parse_one_page(html): print(item) write_to_file(item) if __name__ == '__main__': main()

單頁的url資訊獲取之後,更改為多程序方式獲取全部!

def main(offset):
    url = 'http://maoyan.com/board/4?offset={}'.format(offset)
    html = get_one_page(url)
    # total = []
    for item in parse_one_page(html):
        print(item)
        # total.extend(item)
        write_to_file(item)
    # save_to_pandas(total)


if __name__ == '__main__':
    import time
    time1 = time.time()

    pool = Pool()
    pool.map(main, [i*10 for i in range(10)])

    # for i in range(10):   單程序
    #     main(i*10)

    time2 = time.time()
    print(time2-time1)

測試單程序2.3s,多程序只需要1s。