利用requests库和正则表达式 抓取猫眼电影TOP100 (requests比urllib使用更方便,由于没有学习HTML系统解析库 选用re)

1.目标 抓取电影名称 时间 评分 图片等

url http://maoyan.com/board/4 结果以文件形式保存

2.分析

offset 代表偏移量 如果为n 电影序号为n+1~n+10 每页显示10个

获取100 分开请求10次 offset 分别为0 10 20...90 利用正则提取相关信息

3.抓取页面

import requests
#爬取第一页 页面信息
def get_one_page(url):
header = {
"User-Agent":"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16",
}
response = requests.get(url,headers=header)
if response.status_code == 200:#判断是否请求成功
return response.text
return None

# 定义一个main函数 调用get_one_page 发送请求 打印结果

def main():
url = 'http://maoyan.com/board/4'
html = get_one_page(url)#调用请求函数
print(html)
main()

分析页面
电影信息对应节点为<dd>
提取排名 class 为 board-index i节点内 正则 <dd>.*?board-index.*?>(.*?)</i>
电影图片 查看为第二个img链接 <dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)"
电影名字 p节点 class 为name <dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>
主演 <dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>
发布时间 <dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>
评分 <dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>

定义分析页面的方法 parse_one_page()

import requests
import re
def get_one_page(url):
header = {
"User-Agent":"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16",
}
response = requests.get(url,headers=header)
if response.status_code == 200:
return response.text
return None def parse_one_page(html):
pattern = re.compile(
'<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>',re.S
)
items = re.findall(pattern,html)
print(items)
# 定义一个main函数 调用get_one_page 发送请求 打印结果
def main():
url = 'http://maoyan.com/board/4'
html = get_one_page(url)
# print(html)
parse_one_page(html)
main()

将匹配结果遍历 生成字典

import requests
import re def get_one_page(url):
header = {
"User-Agent":"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16",
}
response = requests.get(url,headers=header)
if response.status_code == 200:
return response.text
return None def parse_one_page(html):# html为网页源码
pattern = re.compile(
'<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>',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()
}
#返回一个生成器 yield # 定义一个main函数 调用get_one_page 发送请求 打印结果
def main():
url = 'http://maoyan.com/board/4'
html = get_one_page(url)
# print(html)
for item in parse_one_page(html):#遍历生成器
print(item)
main() 写入文件 将提取结果 写入文件 通过json库 的dumps() 实现字典的序列化 指定ensure_ascii 参数为 False
#写入文件
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')

整合代码 单页面电影提取

import requests
import re
import json
# 请求页面
def get_one_page(url):
header = {
"User-Agent":"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16",
}
response = requests.get(url,headers=header)
if response.status_code == 200:
return response.text
return None #解析页面
def parse_one_page(html):# html为网页源码
pattern = re.compile(
'<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>',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()
}
#返回一个生成器 yield #写入文件
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') # 定义一个main函数 调用get_one_page 发送请求 打印结果
def main():
url = 'http://maoyan.com/board/4'
html = get_one_page(url)
# print(html)
for item in parse_one_page(html):#遍历生成器
write_to_file(item)
main()

分页爬取

# 定义一个main函数 调用get_one_page 发送请求 打印结果

def main(offset):
url = 'http://maoyan.com/board/4?offset=' + str(offset)
html = get_one_page(url)
# print(html)
for item in parse_one_page(html):#遍历生成器
write_to_file(item) if __name__ == '__main__':
for i in range(10):
main(offset = i *10)

整理代码

#-*-coding:utf-8-*-

import requests #请求库
import re #正则模块
import json #json模块
import time #时间模块
from requests.exceptions import RequestException#捕获异常模块
# 请求页面
def get_one_page(url):
#异常处理
try:
header = {
"User-Agent":"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16",
}
response = requests.get(url,headers=header)
# 判断状态码是否为200
if response.status_code == 200:
return response.text
return None
except RequestException:
return None #解析页面
def parse_one_page(html):# html为网页源码
#定义爬取规则
pattern = re.compile(
'<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>',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()
}
#返回一个生成器 yield #写入文件
def write_to_file(content):
with open('result.txt','a',encoding='utf-8') as f:
# print(type(json.dumps(content)))
# ensure_ascii=False 保证输出结果为中文
f.write(json.dumps(content,ensure_ascii=False)+'\n') # 定义一个main函数 调用get_one_page 发送请求 参数offset 网页偏移量
def main(offset):
#拼接url地址
url = 'http://maoyan.com/board/4?offset=' + str(offset)
# 请求函数
html = get_one_page(url)
# print(html)
# 解析函数 和 文件保存函数
for item in parse_one_page(html):#遍历生成器
write_to_file(item) if __name__ == '__main__':
for i in range(10):
main(offset = i *10)
#延时处理
time.sleep(3)

# 最基础的实例 做好总结

Python3编写网络爬虫04-爬取猫眼电影排行实例的更多相关文章

  1. python3编写网络爬虫19-app爬取

    一.app爬取 前面都是介绍爬取Web网页的内容,随着移动互联网的发展,越来越多的企业并没有提供Web页面端的服务,而是直接开发了App,更多信息都是通过App展示的 App爬取相比Web端更加容易 ...

  2. 爬虫--requests爬取猫眼电影排行榜

    '''目标:使用requests分页爬取猫眼电影中榜单栏目中TOP100榜的所有电影信息,并将信息写入文件URL地址:http://maoyan.com/board/4 其中参数offset表示其实条 ...

  3. Python爬虫项目--爬取猫眼电影Top100榜

    本次抓取猫眼电影Top100榜所用到的知识点: 1. python requests库 2. 正则表达式 3. csv模块 4. 多进程 正文 目标站点分析 通过对目标站点的分析, 来确定网页结构,  ...

  4. python学习(23)requests库爬取猫眼电影排行信息

    本文介绍如何结合前面讲解的基本知识,采用requests,正则表达式,cookies结合起来,做一次实战,抓取猫眼电影排名信息. 用requests写一个基本的爬虫 排行信息大致如下图 网址链接为ht ...

  5. 零基础Python爬虫实现(爬取最新电影排行)

    提示:本学习来自Ehco前辈的文章, 经过实现得出的笔记. 目标网站 http://dianying.2345.com/top/ 网站结构 要爬的部分,在ul标签下(包括li标签), 大致来说迭代li ...

  6. Python爬取猫眼电影排行

    import requests import pyquery def crawl_page(url: str) -> None: headers = { 'user-agent': 'Mozil ...

  7. 爬虫系列(1)-----python爬取猫眼电影top100榜

    对于Python初学者来说,爬虫技能是应该是最好入门,也是最能够有让自己有成就感的,今天在整理代码时,整理了一下之前自己学习爬虫的一些代码,今天先上一个简单的例子,手把手教你入门Python爬虫,爬取 ...

  8. 50 行代码教你爬取猫眼电影 TOP100 榜所有信息

    对于Python初学者来说,爬虫技能是应该是最好入门,也是最能够有让自己有成就感的,今天,恋习Python的手把手系列,手把手教你入门Python爬虫,爬取猫眼电影TOP100榜信息,将涉及到基础爬虫 ...

  9. PYTHON 爬虫笔记八:利用Requests+正则表达式爬取猫眼电影top100(实战项目一)

    利用Requests+正则表达式爬取猫眼电影top100 目标站点分析 流程框架 爬虫实战 使用requests库获取top100首页: import requests def get_one_pag ...

随机推荐

  1. jQgrid学习笔记

    jQgrid学习笔记

  2. 深入JAVA注解(Annotation):自定义注解 (转)

    原文出自:http://blog.csdn.net/yjclsx/article/details/52101922 一.基础知识:元注解 要深入学习注解,我们就必须能定义自己的注解,并使用注解,在定义 ...

  3. 记录前台页面一些jQuery笔记

    不知不觉工作两个月了,在这两个月,我成长很快学的很多,刚开始的时候,很多问题不懂,很多技术不会,当然作为实习阶段,很多不会的问题我都会去请教别人,在这里得感谢那些帮助我的人,但是经常去问别人问题,首先 ...

  4. SQL 两个时间获取相差秒数

    SELECT DATEDIFF(SECOND, '2005-12-31 23:59:00', '2006-01-01 00:00:00');

  5. SQL 查看表每一个列的名字以及类型

    select a.name,b.name from sys.columns as a join sys.types as b on a.system_type_id=b.system_type_id ...

  6. ASP.NET Identity 一 (转载)

    来源:http://www.cnblogs.com/r01cn/p/5194257.html 注:本文是[ASP.NET Identity系列教程]的第一篇.本系列教程详细.完整.深入地介绍了微软的A ...

  7. 【Core】创建简单的Core MVC项目

    创建项目: 首先:打开vs选中新建项目- >选中.NET Core - >ASP.NET Core Web应用程序: 然后:在选择web应用程序,注意上面要选中.net Core 别选错了 ...

  8. 140 - The 12th Zhejiang Provincial Collegiate Programming Contest(第三部分)

    Earthstone Keeper Time Limit: 4 Seconds      Memory Limit: 65536 KB Earthstone Keeper is a famous ro ...

  9. linux学习笔记-目录相关知识

    我的邮箱地址:zytrenren@163.com欢迎大家交流学习纠错! linux的目录结构及作用是根据fhs标准定制的,以下列出一些常用的目录的作用,以及fhs官方网站的连接 FHS官方网站的连接: ...

  10. python学习之解决中英文混合输出的排版问题

    在python的格式输出时常使用format()方法,其中的多余空间默认使用英文空格作为占位符,不方便中英混合时的格式输出,因此我们要为其中的中文字符串使用占字符较大的中文空格符作为多余空间的占位符. ...