defparse_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] }
defwrite_to_file(content): with open('猫眼电影TOP100.txt','a',encoding='utf-8') as f: f.write(json.dumps(content,ensure_ascii=False) + '\n') f.close defmain(offset): url = 'http://maoyan.com/board/4?offset' + str(offset) #url设置偏移量 html = get_one_page(url) #print(html) items = parse_one_page(html) for item in items: print(item) write_to_file(item) if __name__ == '__main__': for i in range(10): main(offset=i * 10) #pool = Pool() # 使用进程池,提高抓取效率(使用多进程需要屏蔽for循环) #pool.map(main,[i*10 for i in range(10)])