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中__call__用法实例
Aug 29 Python
python开发之基于thread线程搜索本地文件的方法
Nov 11 Python
python编写微信远程控制电脑的程序
Jan 05 Python
Python数字图像处理之霍夫线变换实现详解
Jan 12 Python
pytorch 把MNIST数据集转换成图片和txt的方法
May 20 Python
在dataframe两列日期相减并且得到具体的月数实例
Jul 03 Python
anaconda如何查看并管理python环境
Jul 05 Python
Spring实战之使用util:命名空间简化配置操作示例
Dec 09 Python
python使用正则表达式(Regular Expression)方法超详细
Dec 30 Python
Python 找出出现次数超过数组长度一半的元素实例
May 11 Python
Expected conditions模块使用方法汇总代码解析
Aug 13 Python
python 开心网和豆瓣日记爬取的小爬虫
May 29 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
整理的9个实用的PHP库简介和下载
2010/11/09 PHP
php中$_REQUEST、$_POST、$_GET的区别和联系小结
2011/11/23 PHP
thinkPHP的表达式查询用法详解
2016/09/14 PHP
Convert Seconds To Hours
2007/06/16 Javascript
jquery中常用的SET和GET
2009/01/13 Javascript
深入领悟JavaScript中的面向对象
2013/11/18 Javascript
document.write的几点使用心得
2014/05/14 Javascript
JavaScript利用append添加元素报错的解决方法
2014/07/01 Javascript
使用AOP改善javascript代码
2015/05/01 Javascript
js动态生成Html元素实现Post操作(createElement)
2015/09/14 Javascript
基于Vue+elementUI实现动态表单的校验功能(根据条件动态切换校验格式)
2019/04/04 Javascript
js实现图片推拉门效果代码实例
2019/05/18 Javascript
Javascript实现简易天数计算器
2020/05/18 Javascript
在Django的视图(View)外使用Session的方法
2015/07/23 Python
Python实现中文数字转换为阿拉伯数字的方法示例
2017/05/26 Python
Python优先队列实现方法示例
2017/09/21 Python
tensorflow实现对图片的读取的示例代码
2018/02/12 Python
python 遍历目录(包括子目录)下所有文件的实例
2018/07/11 Python
PowerBI和Python关于数据分析的对比
2019/07/11 Python
Django 路由控制的实现
2019/07/17 Python
在pycharm中显示python画的图方法
2019/08/31 Python
浅谈Django2.0 加xadmin踩的坑
2019/11/15 Python
python scrapy重复执行实现代码详解
2019/12/28 Python
Python基于gevent实现文件字符串查找器
2020/08/11 Python
Python数据模型与Python对象模型的相关总结
2021/01/26 Python
英国拳击装备购物网站:RDX Sports
2018/01/23 全球购物
Coccinelle官网:意大利的著名皮具品牌
2019/05/15 全球购物
俄罗斯美容和健康网上商店:Созвездие Красоты
2019/07/23 全球购物
物理系毕业生自荐信
2013/11/01 职场文书
美发活动策划书
2014/01/14 职场文书
竞争性谈判邀请书
2014/02/06 职场文书
《青山处处埋忠骨》教学反思
2014/04/22 职场文书
校园绿化美化方案
2014/06/08 职场文书
城市规划应届毕业生自荐信
2014/07/04 职场文书
求职自荐信怎么写
2015/03/04 职场文书
假如给我三天光明读书笔记
2015/06/26 职场文书