import json import re from multiprocessing.pool import Pool import requests from requests import RequestException def get_one_page(url): try: response =requests.get(url) if response.status_code==200: return response.text except RequestException: return None def parse_one_page(html): ''' 对界面进行解析 :param html: :return: ''' pattern=re.compile('<dd>.*?board-index.*?>(d+)</i>.*?data-src="(.*?)".*?name"><a .*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(d+)</i>',re.S)#正则表达式 items=re.findall(pattern,html) for item in items: yield { '序号':item[0], '图片':item[1], '电影名': item[2], '主演': item[3].strip()[3:], '上映时间': item[4].strip()[5:], '评分': item[5]+item[6], } def write_to_file(content): ''' 写入文本 :param content: :return: ''' with open('猫眼top100.txt', 'a',encoding='utf-8')as f:#打开文件,如果没有就创建,encoding 指定编码方式 f.write(json.dumps(content,ensure_ascii=False)+' ')#ensure_ascii=False以指定的方式编码 def main(offset): url='https://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) # print(html) if __name__ == '__main__': for i in range (10): main(i*10) # pool=Pool()#多线程 进程池 # pool.map(main,[i*10 for i in range (10)])