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计算三角函数之asin()方法的使用
May 15 Python
python中import学习备忘笔记
Jan 24 Python
Python实现的弹球小游戏示例
Aug 01 Python
Python编程使用tkinter模块实现计算器软件完整代码示例
Nov 29 Python
在cmder下安装ipython以及环境的搭建
Oct 19 Python
对python 树状嵌套结构的实现思路详解
Aug 09 Python
python实现的读取网页并分词功能示例
Oct 29 Python
opencv3/C++实现视频背景去除建模(BSM)
Dec 11 Python
基于pytorch的lstm参数使用详解
Jan 14 Python
在pytorch 中计算精度、回归率、F1 score等指标的实例
Jan 18 Python
Python实现名片管理系统
Feb 14 Python
python3 自动打印出最新版本执行的mysql2redis实例
Apr 09 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获取指定日期所在月的开始日期与结束日期
2013/08/01 PHP
php准确获取文件MIME类型的方法
2015/06/17 PHP
Json_encode防止汉字转义成unicode的方法
2016/02/25 PHP
thinkPHP框架实现的无限回复评论功能示例
2018/06/09 PHP
jQuery延迟加载图片插件Lazy Load使用指南
2015/03/25 Javascript
浅析JavaScript中的事件机制
2015/06/04 Javascript
把Node.js程序加入服务实现随机启动
2015/06/25 Javascript
jquery实现带渐变淡入淡出并向右依次展开的多级菜单效果实例
2015/08/22 Javascript
解决js函数闭包内存泄露问题的办法
2016/01/25 Javascript
js中class的点击事件没有效果的解决方法
2016/10/13 Javascript
bootstrap datetimepicker2.3.11时间插件使用
2016/11/19 Javascript
Node.js 使用命令行工具检查更新
2017/06/08 Javascript
layui(1.0.9)文件上传upload,前后端的实例代码
2019/09/26 Javascript
vue指令v-html使用过滤器filters功能实例
2019/10/25 Javascript
js实现计时器秒表功能
2019/12/16 Javascript
实用的 vue tags 创建缓存导航的过程实现
2020/12/03 Vue.js
javascript中call,apply,bind的区别详解
2020/12/11 Javascript
在Python中使用cookielib和urllib2配合PyQuery抓取网页信息
2015/04/25 Python
在Python中用has_key()方法查找键是否存在的教程
2015/05/21 Python
使用FastCGI部署Python的Django应用的教程
2015/07/22 Python
python学生信息管理系统(完整版)
2020/04/05 Python
Django之无名分组和有名分组的实现
2019/04/16 Python
pywinauto自动化操作记事本
2019/08/26 Python
python 读取数据库并绘图的实例
2019/12/03 Python
python argparse模块通过后台传递参数实例
2020/04/20 Python
咖啡为什么会有酸味?你喝到的咖啡為什麼是酸的?
2021/03/17 冲泡冲煮
H5新属性audio音频和video视频的控制详解(推荐)
2016/12/09 HTML / CSS
AC Lens:购买隐形眼镜
2017/02/26 全球购物
董事长岗位职责
2013/11/30 职场文书
出纳工作岗位责任制
2014/02/02 职场文书
电视购物广告词
2014/03/19 职场文书
公证委托书模板
2014/04/03 职场文书
廉洁教育学习材料
2014/05/19 职场文书
整改落实情况汇报材料
2014/10/29 职场文书
2015年乡镇纪委工作总结
2015/05/26 职场文书
优化经济发展环境工作总结
2015/08/11 职场文书