python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例


Posted in Python onMarch 10, 2020

使用Python爬虫库requests多线程抓取猫眼电影TOP100思路:

  1. 查看网页源代码
  2. 抓取单页内容
  3. 正则表达式提取信息
  4. 猫眼TOP100所有信息写入文件
  5. 多线程抓取
  • 运行平台:windows
  • Python版本:Python 3.7.
  • IDE:Sublime Text
  • 浏览器:Chrome浏览器

1.查看猫眼电影TOP100网页原代码

按F12查看网页源代码发现每一个电影的信息都在“<dd></dd>”标签之中。

python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

点开之后,信息如下:

python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

2.抓取单页内容

在浏览器中打开猫眼电影网站,点击“榜单”,再点击“TOP100榜”如下图:

python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

接下来通过以下代码获取网页源代码:

#-*-coding:utf-8-*-
import requests
from requests.exceptions import RequestException
 
#猫眼电影网站有反爬虫措施,设置headers后可以爬取
headers = {
	'Content-Type': 'text/plain; charset=UTF-8',
	'Origin':'https://maoyan.com',
	'Referer':'https://maoyan.com/board/4',
	'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
	}
 
#爬取网页源代码
def get_one_page(url,headers):
	try:
		response =requests.get(url,headers =headers)
		if response.status_code == 200:
			return response.text
		return None
	except RequestsException:
		return None
 
def main():
	url = "https://maoyan.com/board/4"
	html = get_one_page(url,headers)
	print(html)
 
if __name__ == '__main__':
	main()

执行结果如下:

python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

3.正则表达式提取信息

上图标示信息即为要提取的信息,代码实现如下:

#-*-coding:utf-8-*-
import requests
import re
from requests.exceptions import RequestException
 
#猫眼电影网站有反爬虫措施,设置headers后可以爬取
headers = {
	'Content-Type': 'text/plain; charset=UTF-8',
	'Origin':'https://maoyan.com',
	'Referer':'https://maoyan.com/board/4',
	'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
	}
 
#爬取网页源代码
def get_one_page(url,headers):
	try:
		response =requests.get(url,headers =headers)
		if response.status_code == 200:
			return response.text
		return None
	except RequestsException:
		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 main():
	url = "https://maoyan.com/board/4"
	html = get_one_page(url,headers)
	for item in parse_one_page(html):
		print(item)
 
if __name__ == '__main__':
	main()

执行结果如下:

python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

4.猫眼TOP100所有信息写入文件

上边代码实现单页的信息抓取,要想爬取100个电影的信息,先观察每一页url的变化,点开每一页我们会发现url进行变化,原url后面多了‘?offset=0',且offset的值变化从0,10,20,变化如下:

python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

代码实现如下:

#-*-coding:utf-8-*-
import requests
import re
import json
import os
from requests.exceptions import RequestException
 
#猫眼电影网站有反爬虫措施,设置headers后可以爬取
headers = {
	'Content-Type': 'text/plain; charset=UTF-8',
	'Origin':'https://maoyan.com',
	'Referer':'https://maoyan.com/board/4',
	'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
	}
 
#爬取网页源代码
def get_one_page(url,headers):
	try:
		response =requests.get(url,headers =headers)
		if response.status_code == 200:
			return response.text
		return None
	except RequestsException:
		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]
		}
#猫眼TOP100所有信息写入文件
def write_to_file(content):
	#encoding ='utf-8',ensure_ascii =False,使写入文件的代码显示为中文
	with open('result.txt','a',encoding ='utf-8') as f:
		f.write(json.dumps(content,ensure_ascii =False)+'\n')
		f.close()
#下载电影封面
def save_image_file(url,path):
 
	jd = requests.get(url)
	if jd.status_code == 200:
		with open(path,'wb') as f:
			f.write(jd.content)
			f.close()
 
def main(offset):
	url = "https://maoyan.com/board/4?offset="+str(offset)
	html = get_one_page(url,headers)
	if not os.path.exists('covers'):
		os.mkdir('covers')	
	for item in parse_one_page(html):
		print(item)
		write_to_file(item)
		save_image_file(item['image'],'covers/'+item['title']+'.jpg')
 
if __name__ == '__main__':
	#对每一页信息进行爬取
	for i in range(10):
		main(i*10)

爬取结果如下:

python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

5.多线程抓取

进行比较,发现多线程爬取时间明显较快:

python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

多线程:

python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

以下为完整代码:

#-*-coding:utf-8-*-
import requests
import re
import json
import os
from requests.exceptions import RequestException
from multiprocessing import Pool
#猫眼电影网站有反爬虫措施,设置headers后可以爬取
headers = {
	'Content-Type': 'text/plain; charset=UTF-8',
	'Origin':'https://maoyan.com',
	'Referer':'https://maoyan.com/board/4',
	'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
	}
 
#爬取网页源代码
def get_one_page(url,headers):
	try:
		response =requests.get(url,headers =headers)
		if response.status_code == 200:
			return response.text
		return None
	except RequestsException:
		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]
		}
#猫眼TOP100所有信息写入文件
def write_to_file(content):
	#encoding ='utf-8',ensure_ascii =False,使写入文件的代码显示为中文
	with open('result.txt','a',encoding ='utf-8') as f:
		f.write(json.dumps(content,ensure_ascii =False)+'\n')
		f.close()
#下载电影封面
def save_image_file(url,path):
 
	jd = requests.get(url)
	if jd.status_code == 200:
		with open(path,'wb') as f:
			f.write(jd.content)
			f.close()
 
def main(offset):
	url = "https://maoyan.com/board/4?offset="+str(offset)
	html = get_one_page(url,headers)
	if not os.path.exists('covers'):
		os.mkdir('covers')	
	for item in parse_one_page(html):
		print(item)
		write_to_file(item)
		save_image_file(item['image'],'covers/'+item['title']+'.jpg')
 
if __name__ == '__main__':
	#对每一页信息进行爬取
	pool = Pool()
	pool.map(main,[i*10 for i in range(10)])
	pool.close()
	pool.join()

本文主要讲解了使用Python爬虫库requests多线程抓取猫眼电影TOP100数据的实例,更多关于Python爬虫库的知识请查看下面的相关链接

Python 相关文章推荐
零基础写python爬虫之urllib2使用指南
Nov 05 Python
python使用点操作符访问字典(dict)数据的方法
Mar 16 Python
python基于右递归解决八皇后问题的方法
May 25 Python
Python中字符串格式化str.format的详细介绍
Feb 17 Python
python3使用flask编写注册post接口的方法
Dec 28 Python
利用Python进行图像的加法,图像混合(附代码)
Jul 14 Python
python同步两个文件夹下的内容
Aug 29 Python
python 上下文管理器及自定义原理解析
Nov 19 Python
Python如何实现后端自定义认证并实现多条件登陆
Jun 22 Python
图解Python中深浅copy(通俗易懂)
Sep 03 Python
Anaconda使用IDLE的实现示例
Sep 23 Python
python 如何用map()函数创建多线程任务
Apr 07 Python
Django 404、500页面全局配置知识点详解
Mar 10 #Python
python使用gdal对shp读取,新建和更新的实例
Mar 10 #Python
Python实现获取当前目录下文件名代码详解
Mar 10 #Python
python爬虫开发之使用python爬虫库requests,urllib与今日头条搜索功能爬取搜索内容实例
Mar 10 #Python
python+gdal+遥感图像拼接(mosaic)的实例
Mar 10 #Python
python获取栅格点和面值的实现
Mar 10 #Python
Python列表切片常用操作实例解析
Mar 10 #Python
You might like
PHP 简单日历实现代码
2009/10/28 PHP
php表单敏感字符过滤类
2014/12/08 PHP
JavaScript中的Location地址对象
2008/01/16 Javascript
Javascript学习笔记2 函数
2010/01/11 Javascript
javascript-简单的日历实现及Date对象语法介绍(附图)
2013/05/30 Javascript
javascript中的Function.prototye.bind
2015/06/25 Javascript
AngularJS $injector 依赖注入详解
2016/09/14 Javascript
对称加密与非对称加密优缺点详解
2017/02/06 Javascript
JAVA中截取字符串substring用法详解
2017/04/14 Javascript
jquery dataTable 后台加载数据并分页实例代码
2017/06/07 jQuery
Angular4学习笔记之实现绑定和分包
2017/08/01 Javascript
node使用Koa2搭建web项目的方法
2017/10/17 Javascript
jQuery选择器之层次选择器用法实例分析
2019/02/19 jQuery
探究一道价值25k的蚂蚁金服异步串行面试题
2020/08/21 Javascript
详解Python中的文本处理
2015/04/11 Python
python中的错误处理
2016/04/10 Python
Python操作MongoDB详解及实例
2017/05/18 Python
python调用OpenCV实现人脸识别功能
2018/05/25 Python
Python获取数据库数据并保存在excel表格中的方法
2019/06/12 Python
Django中使用haystack+whoosh实现搜索功能
2019/10/08 Python
python 计算积分图和haar特征的实例代码
2019/11/20 Python
python3 动态模块导入与全局变量使用实例
2019/12/22 Python
TFRecord文件查看包含的所有Features代码
2020/02/17 Python
TensorFlow实现模型断点训练,checkpoint模型载入方式
2020/05/26 Python
keras使用Sequence类调用大规模数据集进行训练的实现
2020/06/22 Python
利用css3实现的简单的鼠标悬停按钮
2014/11/04 HTML / CSS
html5 视频播放解决方案
2016/11/06 HTML / CSS
用Python匹配HTML tag的时候,<.*>和<.*?>有什么区别
2012/11/04 面试题
经济信息系毕业生自荐信范文
2014/03/15 职场文书
校园活动宣传方案
2014/03/28 职场文书
美容院店长岗位职责
2014/04/08 职场文书
项目建议书范文
2014/05/12 职场文书
皇城相府导游词
2015/02/06 职场文书
爱鸟护鸟的宣传语
2015/07/13 职场文书
只需要12页,掌握撰写一流商业计划书的技巧
2019/05/07 职场文书
Python带你从浅入深探究Tuple(基础篇)
2021/05/15 Python