Python3爬取猫眼电影信息

import json
import requests
from requests.exceptions import RequestException
import re
import time #爬取猫眼电影信息 def get_one_page(url):
#增加了User-Agent识别,需要在headers中添加User-Agent参数。
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 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_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]
} #写入文件
def write_to_file(content):
with open('result.txt', 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n') def main(offset):
url = 'http://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) #分页爬取
if __name__ == '__main__':
for i in range(10):
main(offset=i * 10)
#延时等待
time.sleep(1)

最新文章

  1. 前端打包构建工具gulp快速入门
  2. GitFlow
  3. GetLastError()函数返回值及含义
  4. [ZigBee] 2、 ZigBee开发环境搭建
  5. HDU 5139 Formula --离线处理
  6. DIjkstra(反向边) POJ 3268 Silver Cow Party || POJ 1511 Invitation Cards
  7. MSCRM 迁移 数据库 服务器
  8. Spring 自动装配 Bean
  9. 使用Yeoman搭建 AngularJS 应用 (8) —— 让我们搭建一个网页应用
  10. Fiddler On Linux
  11. 负载均衡-多台机子session不起效:把php.ini中file改为memcache存储
  12. 使用wfastcgi在IIS上部署Python Flask应用
  13. eclipse+python+Anaconda ML环境搭建
  14. centos 安装 redis3.2.0 集群
  15. Image 对象
  16. InnoDB的行溢出数据,Char的行结构存储
  17. php生成二维码的几种方式整理及使用实例
  18. Luogu P3600 随机数生成器(期望+dp)
  19. 转:JMeter压力测试及并发量计算
  20. Arbiter

热门文章

  1. (开源项目)abattoir unity游戏
  2. Solon rpc 之 SocketD 协议 - 消息上报模式
  3. shell 脚本安装Tomcat和java
  4. PAT甲级 1155 Heap Paths (30分) 堆模拟
  5. Linux find 命令的初步实现(C++)
  6. Neo4j 图数据库查询
  7. 【Linux】NFS相关小问题
  8. AWD生存之道
  9. .NET Core部署到linux(CentOS)最全解决方案,进阶篇(Supervisor+Nginx)
  10. [Usaco2008 Feb]Line连线游戏