猫眼电影榜单TOP100爬取项目

猫眼电影top100爬取

全代码如下:

import requests
import re
import json
# from multiprocessing import Pool  ##多进程爬取时需要

def getonepage(url):
    try:
        r=requests.get(url)
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except Exception as err:
        print(str(err))

def parseonepage(html):
    pat=re.compile('
.*?board-index.*?>(\d+).*?data-src="(.*?)".*?name"> +'.*?>(.*?).*?star">(.*?)

.*?releasetime">(.*?)

'
+'.*?integer">(.*?).*?fraction">(.*?).*?
'
,re.S) # 需要注意正则表达式的写法 items=re.findall(pat,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:], #strip()为了去除末尾的换行符 'score':item[5]+item[6] } #构造生成器 def writetofile(content): with open('result.txt','a',encoding='utf-8') as f: #a表示往后追加存储 f.write(json.dumps(content,ensure_ascii=False)+'\n') #由于item是字典类型,需用json.dumps()来解析,且保证中文存储 f.close() def main(offset): url='http://maoyan.com/board/4?offset='+str(offset) html = getonepage(url) for item in parseonepage(html): print(item) writetofile(item) if __name__=='__main__': for i in range(10): main(i*10) #pool=Pool() #pool.map(main,[i*10 for i in range(10)]) #多进程爬取时代码

你可能感兴趣的:(python,爬虫)