#抓取猫眼热映口碑榜 import json import requests from requests.exceptions import RequestException from lxml import etree import time #抓取首页 def get_one_page(url): try: headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36' } response = requests.get(url, headers=headers) if response.status_code == 200: return response.text return None except RequestException: return None def parse_html(html): html = etree.HTML(html) result = html.xpath('//dl[@class="board-wrapper"]/dd') for line in result: id = line.xpath('i/text()') title = line.xpath('div/div/div/p/a/@title') actor = line.xpath('div/div/div/p[@class="star"]/text()') time = line.xpath('div/div/div/p[@class="releasetime"]/text()') for i in actor: actor = i.strip() yield { 'id': id[0], 'title': title[0], 'actor': actor, 'time': time[0][3:], } def write_to_file(content): with open('result.txt', 'a', encoding='utf-8') as f: f.write(json.dumps(content, ensure_ascii=False) + ' ') def main(): url = 'http://maoyan.com/board' html = get_one_page(url) for item in parse_html(html): print(item) write_to_file(item) time.sleep(1) if __name__ == '__main__': main()
输出结果: {'id': '1', 'title': '狂暴巨兽', 'actor': '主演:道恩·强森,娜奥米·哈里斯,杰弗里·迪恩·摩根', 'time': '间:2018-04-13'} {'id': '2', 'title': '巴霍巴利王2:终结', 'actor': '主演:帕拉巴斯,拉纳·达格巴提,安努舒卡·谢蒂', 'time': '间:2018-05-04'} {'id': '3', 'title': '超时空同居', 'actor': '主演:雷佳音,佟丽娅,徐峥', 'time': '间:2018-05-18'} {'id': '4', 'title': '复仇者联盟3:无限战争', 'actor': '主演:小罗伯特·唐尼,克里斯·海姆斯沃斯,马克·鲁法洛', 'time': '间:2018-05-11'} {'id': '5', 'title': '完美陌生人', 'actor': '主演:朱塞佩·巴蒂斯通,安娜·福列塔,马可·贾利尼', 'time': '间:2018-05-25'} {'id': '6', 'title': '青年马克思', 'actor': '主演:奧古斯特·迪赫,史特凡·柯纳斯克,薇姬·克里普斯', 'time': '间:2018-05-05'} {'id': '7', 'title': '昼颜', 'actor': '主演:上户彩,斋藤工,伊藤步', 'time': '间:2018-05-18'} {'id': '8', 'title': '我是你妈', 'actor': '主演:闫妮,邹元清,吴若甫', 'time': '间:2018-05-11'} {'id': '9', 'title': '西小河的夏天', 'actor': '主演:张颂文,谭卓,顾宝明', 'time': '间:2018-05-25'} {'id': '10', 'title': '哆啦A梦:大雄的金银岛', 'actor': '主演:水田山葵,大原惠美,嘉数由美', 'time': '间:2018-06-01'}
参考链接:https://www.jianshu.com/p/7041a7ba7fe0