Python3爬取猫眼电影信息
2024-09-04 20:28:59
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)
最新文章
- 前端打包构建工具gulp快速入门
- GitFlow
- GetLastError()函数返回值及含义
- [ZigBee] 2、 ZigBee开发环境搭建
- HDU 5139 Formula --离线处理
- DIjkstra(反向边) POJ 3268 Silver Cow Party || POJ 1511 Invitation Cards
- MSCRM 迁移 数据库 服务器
- Spring 自动装配 Bean
- 使用Yeoman搭建 AngularJS 应用 (8) —— 让我们搭建一个网页应用
- Fiddler On Linux
- 负载均衡-多台机子session不起效:把php.ini中file改为memcache存储
- 使用wfastcgi在IIS上部署Python Flask应用
- eclipse+python+Anaconda ML环境搭建
- centos 安装 redis3.2.0 集群
- Image 对象
- InnoDB的行溢出数据,Char的行结构存储
- php生成二维码的几种方式整理及使用实例
- Luogu P3600 随机数生成器(期望+dp)
- 转:JMeter压力测试及并发量计算
- Arbiter
热门文章
- (开源项目)abattoir unity游戏
- Solon rpc 之 SocketD 协议 - 消息上报模式
- shell 脚本安装Tomcat和java
- PAT甲级 1155 Heap Paths (30分) 堆模拟
- Linux find 命令的初步实现(C++)
- Neo4j 图数据库查询
- 【Linux】NFS相关小问题
- AWD生存之道
- .NET Core部署到linux(CentOS)最全解决方案,进阶篇(Supervisor+Nginx)
- [Usaco2008 Feb]Line连线游戏