python3通過(guò)正則抓取貓眼前100電影

import json

import requests

import re

import time

from requests.exceptions import RequestException

def get_one_page(url):

? ? headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36'

}

????response = requests.get(url,headers=headers)

????if response.status_code == 200:

????????return response.text

????return None

def parse_one_page(html):

????pattern = re.compile('.*?board-index.*?>(.*?).*?data-src="(.*?)".*?alt="(.*?)".*?>.*?.*?star.*?>(.*?).*?releasetime.*?>(.*?).*?integer.*?>(.*?).*?fraction.*?>(.*?).*?',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:

????????????print(type(json.dumps(content)))

????????????f.write(json.dumps(content,ensure_ascii=False)+'\n')

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(offset=i * 10)

? ? ? ? ? time.sleep(1)


這里就是顯示的部分內(nèi)容。

剛開(kāi)始正則匹配的時(shí)候,最好能夠一小段一小段的匹配,與網(wǎng)頁(yè)源代碼對(duì)照,提取自己需要的內(nèi)容。代碼排版較亂,直接復(fù)制過(guò)去是無(wú)法成功的。

僅供參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容