爬虫(七):爬取猫眼电影top100
一:分析网站
目标站和目标数据
目标地址:http://maoyan.com/board/4?offset=20
目标数据:目标地址页面的电影列表,包括电影名,电影图片,主演,上映日期以及评分。
二:上代码
(1):导入相应的包
import requests
from requests.exceptions import RequestException # 处理请求异常
import re
import pymysql
import json
from multiprocessing import Pool
(2):分析网页

通过检查发现需要的内容位于网页中的<dd>标签内。通过翻页发现url中的参数的变化。
(3):获取html网页
# 获取一页的数据
def get_one_page(url):
# requests会产生异常
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200: # 状态码是200表示成功
return response.text
else:
return None
except RequestException:
return None
(4):通过正则提取需要的信息 --》正则表达式详情
# 解析网页内容
def parse_one_page(html):
pattern = re.compile(
'<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?class="name"><a.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>',
re.S) # re.S可以匹配任意字符包括换行
items = re.findall(pattern, html) # 将括号中的内容提取出来
for item in items:
yield { # 构造一个生成器
'index': item[0].strip(),
'title': item[2].strip(),
'actor': item[3].strip()[3:],
'score': ''.join([item[5].strip(), item[6].strip()]),
'pub_time': item[4].strip()[5:],
'img_url': item[1].strip(),
}
(5):将获取的内容存入mysql数据库
# 连接数据库,首先要在本地创建好数据库
def commit_to_sql(dic):
conn = pymysql.connect(host='localhost', port=3306, user='mydb', passwd='', db='maoyantop100',
charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 设置游标的数据类型为字典
sql = '''insert into movies_top_100(mid,title,actor,score,pub_time,img_url) values("%s","%s","%s","%s","%s","%s")''' % (
dic['index'], dic['title'], dic['actor'], dic['score'], dic['pub_time'], dic['img_url'],)
cursor.execute(sql) # 执行sql语句并返回受影响的行数
# # 提交
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
(6):主程序及运行
def main(url):
html = get_one_page(url)
for item in parse_one_page(html):
print(item)
commit_to_sql(item) if __name__ == '__main__':
urls = ['http://maoyan.com/board/4?offset={}'.format(i) for i in range(0, 100, 10)]
# 使用多进程
pool = Pool()
pool.map(main, urls)
(7):最后的结果

完整代码:
# -*- coding: utf-8 -*-
# @Author : FELIX
# @Date : 2018/4/4 9:29 import requests
from requests.exceptions import RequestException
import re
import pymysql
import json
from multiprocessing import Pool # 连接数据库
def commit_to_sql(dic):
conn = pymysql.connect(host='localhost', port=3306, user='wang', passwd='', db='maoyantop100',
charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 设置游标的数据类型为字典
sql = '''insert into movies_top_100(mid,title,actor,score,pub_time,img_url) values("%s","%s","%s","%s","%s","%s")''' % (
dic['index'], dic['title'], dic['actor'], dic['score'], dic['pub_time'], dic['img_url'],)
cursor.execute(sql) # 执行sql语句并返回受影响的行数
# # 提交
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close() # 获取一页的数据
def get_one_page(url):
# requests会产生异常
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200: # 状态码是200表示成功
return response.text
else:
return None
except RequestException:
return None # 解析网页内容
def parse_one_page(html):
pattern = re.compile(
'<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?class="name"><a.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>',
re.S) # re.S可以匹配任意字符包括换行
items = re.findall(pattern, html) # 将括号中的内容提取出来
for item in items:
yield { # 构造一个生成器
'index': item[0].strip(),
'title': item[2].strip(),
'actor': item[3].strip()[3:],
'score': ''.join([item[5].strip(), item[6].strip()]),
'pub_time': item[4].strip()[5:],
'img_url': item[1].strip(),
}
# print(items) def write_to_file(content):
with open('result.txt', 'a', encoding='utf8')as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n') ii = 0 def main(url):
html = get_one_page(url)
for item in parse_one_page(html):
global ii
print(ii, item)
ii = ii + 1
commit_to_sql(item)
write_to_file(item) # print(html) if __name__ == '__main__':
urls = ['http://maoyan.com/board/4?offset={}'.format(i) for i in range(0, 100, 10)]
# 使用多进程
pool = Pool()
pool.map(main, urls)
爬虫(七):爬取猫眼电影top100的更多相关文章
- Python爬虫项目--爬取猫眼电影Top100榜
本次抓取猫眼电影Top100榜所用到的知识点: 1. python requests库 2. 正则表达式 3. csv模块 4. 多进程 正文 目标站点分析 通过对目标站点的分析, 来确定网页结构, ...
- 爬虫系列(1)-----python爬取猫眼电影top100榜
对于Python初学者来说,爬虫技能是应该是最好入门,也是最能够有让自己有成就感的,今天在整理代码时,整理了一下之前自己学习爬虫的一些代码,今天先上一个简单的例子,手把手教你入门Python爬虫,爬取 ...
- 50 行代码教你爬取猫眼电影 TOP100 榜所有信息
对于Python初学者来说,爬虫技能是应该是最好入门,也是最能够有让自己有成就感的,今天,恋习Python的手把手系列,手把手教你入门Python爬虫,爬取猫眼电影TOP100榜信息,将涉及到基础爬虫 ...
- PYTHON 爬虫笔记八:利用Requests+正则表达式爬取猫眼电影top100(实战项目一)
利用Requests+正则表达式爬取猫眼电影top100 目标站点分析 流程框架 爬虫实战 使用requests库获取top100首页: import requests def get_one_pag ...
- # [爬虫Demo] pyquery+csv爬取猫眼电影top100
目录 [爬虫Demo] pyquery+csv爬取猫眼电影top100 站点分析 代码君 [爬虫Demo] pyquery+csv爬取猫眼电影top100 站点分析 https://maoyan.co ...
- 40行代码爬取猫眼电影TOP100榜所有信息
主要内容: 一.基础爬虫框架的三大模块 二.完整代码解析及效果展示 1️⃣ 基础爬虫框架的三大模块 1.HTML下载器:利用requests模块下载HTML网页. 2.HTML解析器:利用re正则表 ...
- 用requests库爬取猫眼电影Top100
这里需要注意一下,在爬取猫眼电影Top100时,网站设置了反爬虫机制,因此需要在requests库的get方法中添加headers,伪装成浏览器进行爬取 import requests from re ...
- python 爬取猫眼电影top100数据
最近有爬虫相关的需求,所以上B站找了个视频(链接在文末)看了一下,做了一个小程序出来,大体上没有修改,只是在最后的存储上,由txt换成了excel. 简要需求:爬虫爬取 猫眼电影TOP100榜单 数据 ...
- # 爬虫连载系列(1)--爬取猫眼电影Top100
前言 学习python有一段时间了,之前一直忙于学习数据分析,耽搁了原本计划的博客更新.趁着这段空闲时间,打算开始更新一个爬虫系列.内容大致包括:使用正则表达式.xpath.BeautifulSoup ...
- 爬虫--requests爬取猫眼电影排行榜
'''目标:使用requests分页爬取猫眼电影中榜单栏目中TOP100榜的所有电影信息,并将信息写入文件URL地址:http://maoyan.com/board/4 其中参数offset表示其实条 ...
随机推荐
- Python+VSCode+Git【转】
Python+VSCode+Git 学习总结 - 秦无邪 - 博客园
- CentOS7安装firewall防火墙
CentOS7之后 , 系统已经推荐了firewall防火墙 , 而不是iptables 主要 : firewall 和 iptables冲突 , 需要禁用其中一个. #停止iptables服务 sy ...
- kubernets 证书过期的问题
.问题起源 kubeadm 是 kubernetes 提供的一个初始化集群的工具,使用起来非常方便.但是它创建的apiserver.controller-manager等证书默认只有一年的有效期,同时 ...
- ios设备app作为蓝牙外设端
苹果手机可以作为蓝牙外设端,被蓝牙中央端来扫描连接交互数据,实现模拟蓝牙外设硬件.通过阅读CoreBluetooth库,可以找到一个CBPeripheralManager的类,该类主要的作用就是允许你 ...
- [LeetCode] 95. 不同的二叉搜索树 II ☆☆☆(递归,n个数组成的所有二叉搜索树)
https://leetcode-cn.com/problems/unique-binary-search-trees-ii/solution/xiang-xi-tong-su-de-si-lu-fe ...
- 3-JavaSe-1-stream-1-流库特征
1.parallelStream可以让流库以并行方式来执行过滤和计数. String content=new String(Files.readAllBytes(Paths.get("D:\ ...
- C#中的struct(结构)为值类型,struct类型全接触
众所周知,struct类型和class类型非常相似,尤其是在C++中,class可以办到的事struct几乎都可以实现.在C#中struc类型依然存在,它的用处相对来说已经显得越来越不重要,这里主要讲 ...
- windows 下 redis 的安装及使用
1.下载及安装redis 下载地址:https://github.com/dmajkic/redis/downloads 找到对应的版本下载安装 打开cmd窗口,用cd命令进入到安装redis的根目录 ...
- TLS1.3对CIP的影响(对密码套件的解释)
1.术语定义的即使(算法)Definition of terms (optional) Cipher Suite :通信数据保护规范,对TLS指定对端身份验证,关键技术机制,后续数据加密和数据验证机 ...
- linux下的缓存机制buffer、cache、swap - 运维总结 ["Cannot allocate memory"问题]
一.缓存机制介绍 在Linux系统中,为了提高文件系统性能,内核利用一部分物理内存分配出缓冲区,用于缓存系统操作和数据文件,当内核收到读写的请求时,内核先去缓存区找是否有请求的数据,有就直接返回,如果 ...