本文共 1476 字,大约阅读时间需要 4 分钟。
来上代码
import requestsimport reimport jsonimport time# 获取一页的数据def get_one_page(url): headers = { "User-Agent": "Mozilla/5.0 (Macintosh; U; Mac OS X Mach-O; en-US; rv:2.0a) Gecko/20040614 Firefox/3.0.0 " } response = requests.get(url, headers=headers) if response.status_code == 200: return response.text return None#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(html) write_to_file(item)#def parse_one_page(html): pattern = re.compile( '
.*?board-index.*?>(.*?).*?data-src="(.*?)".*?name.*?a.*?>(.*?).*?star.*?>(.*?) .*?releasetime.*?>(.*?) .*?integer.*?>(.*?).*?fraction.*?>(.*?).*? ', re.S ) items = re.findall(pattern, html) print(items) for item in items: yield {
'index': item[0], 'image': item[1], 'title': item[2].strip(), 'actor': item[3].strip()[3:] if len(item[3]) > 3 else '', 'time': item[4].strip()[5:] if len(item[4]) > 5 else '', 'score': item[5].strip() + item[6].strip() }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')if __name__ == '__main__': for i in range(10): main(offset=i * 10) time.sleep(1)
可以关注微信公众号:幽灵邀请函 获取更多学习资源
转载地址:http://xnuzi.baihongyu.com/