靜覓爬蟲學習筆記8-爬取貓眼電影


  不知道是不是我學習太晚的原因,貓眼電影這網站我用requests進行爬取源碼直接返回給我一個您的訪問被禁止。作為萌新的我登時就傻了,還好認真聽了之前的課,直接換selenium抓了源碼,雖然效率慘不忍睹,但多少也能運行了,下面上代碼

import json
import requests
import re
from requests.exceptions import RequestException
from multiprocessing import Pool
from selenium import webdriver


def get_one_page(url):                  # 獲取網頁源碼
    browser = webdriver.Chrome()
    try:
        browser.get(url)
        return browser.page_source
    finally:
        browser.close()


def  parse_one_page(html):                 # 利用正則表達式提取內容
    pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><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],
            'actor':item[3].strip()[3:],
            'time':item[4].strip()[5:],
            'score':item[5]+item[6]
        }


def write_to_file(content):                 # 寫入文件
    with open('result.txt','a',encoding='utf-8') as f:
        f.write(json.dumps(content,ensure_ascii=False) + '\n')
        f.close()


def main(offset):
    url="http://maoyan.com/board/4?offset=" + str(offset)
    html = get_one_page(url)
    for item in parse_one_page(html):
        print(item)
        write_to_file(item)


if __name__ == '__main__':
    for i in range(10):
        main(i*10)
    #多線程寫法,實測不是很好用,因為同時打開多個網頁,抓取結果容易亂序
    """
    pool = Pool()
    pool.map(main,[i*10 for i in range(10)])
    """

多線程那塊這寫法不太好用....

而且有的時候爬取的數據不足100個,會漏掉1到2個,而且每次漏掉的還是不同的數據,萌新求教這是為何


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM