抓取猫眼电影top100的正则、bs4、pyquery、xpath实现方法
import requests
import re
import json
import time
from bs4 import BeautifulSoup
from pyquery import PyQuery as pq
from lxml import etree
# 获取页面源码
def get_one_page(url):
try:
headers = { # 伪装请求头
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36'
}
response = requests.get(url, headers=headers) # 构造响应
if response.status_code == 200: # 判断状态码
return response.text
return None
except requests.exceptions.RequestException as r:
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表达式的函数是特殊的函数,叫做生成器函数(generator function),被调用时将返回一个迭代器(iterator),调用时可以使用next或send(msg)。它的用法与return相似,区别在于它会记住上次迭代的状态,继续执行。
yield{ # 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()
}
#Xpath提取信息
def xpath_demo(html):
html=etree.HTML(html)
str1='//dd['
for i in range(10):
yield{ # yield关键字
'index': html.xpath(str1+str(i)+']/i/text()'),
'image': html.xpath(str1+str(i)+']/a/img[@class="board-img"]/@data-src'),
'title': html.xpath(str1+str(i)+']//p/a[@data-act="boarditem-click"]/text()'),
'actor': ''.join(html.xpath(str1+str(i)+']//p[@class="star"]/text()')).strip(),
'time': html.xpath(str1+str(i)+']//p[@class="releasetime"]/text()'),
'score': ''.join(html.xpath(str1+str(i)+']//p[@class="score"]/i/text()')),
}
# bs4提取关键信息
def bs4_demo(html):
soup = BeautifulSoup(html, 'lxml')
# pq=PyQuery(html)
# for item in pq('dd img/.board-img')
for dd in soup.find_all(name='dd'):
yield{
'index': dd.find(name='i', attrs={'class': 'board-index'}).string.strip(),#去掉前后空格
'image': dd.find(name='img', attrs={'class': 'board-img'})['data-src'],
'title': dd.find(name='p', attrs={'class': 'name'}).string.strip(),
'actor': dd.find(name='p', attrs={'class': 'star'}).string.strip(),
'time': dd.find(name='p', attrs={'class': 'releasetime'}).string.strip(),
'score': dd.find(name='i', attrs={'class': 'integer'}).string+dd.find(name='i', attrs={'class': 'fraction'}).string
}
#pyquery css筛选信息
def pyquery_demo(html):
doc=pq(html)
for dd in doc('dd').items():
yield{
'index': dd.find('i.board-index').text(),#获取文本
'image': dd.find('img.board-img').attr('data-src'),#获取属性
'title': dd.find('p.name a').text(),
'actor': dd.find('p.star').text(),
'time': dd.find('p.releasetime').text(),
'score': dd.find('p.score i.integer').text()+dd.find('p.score i.fraction').text()
}
def write_to_file(content):
with open('/Users/zz/Desktop/result.txt', 'a', encoding='utf-8') as f:
# json.dumps()实现字典的序列化,ensure_ascii=False保证输出非Unicode编码
f.write(json.dumps(content, ensure_ascii=False)+'/n')
def main(offset):
url = 'https://maoyan.com/board/4?offset='+str(offset)
html = get_one_page(url)
# for item in parse_one_page(html):
#for item in bs4_demo(html):
#for item in pyquery_demo(html):
for item in xpath_demo(html):
print(item)
# write_to_file(item) # 写入文件
if __name__ == '__main__': # 是否从控制台执行
for i in range(10):
main(offset=i*10)
time.sleep(1)#避免操作过快被识别
抓取猫眼电影top100的正则、bs4、pyquery、xpath实现方法的更多相关文章
- Python Spider 抓取猫眼电影TOP100
""" 抓取猫眼电影TOP100 """ import re import time import requests from bs4 im ...
- Python爬虫之requests+正则表达式抓取猫眼电影top100以及瓜子二手网二手车信息(四)
requests+正则表达式抓取猫眼电影top100 一.首先我们先分析下网页结构 可以看到第一页的URL和第二页的URL的区别在于offset的值,第一页为0,第二页为10,以此类推. 二.< ...
- 爬虫_python3_抓取猫眼电影top100
使用urllib,request,和正则表达式,多线程进行秒抓,以及异常处理结果: import urllib,re,json from multiprocessing import Pool#多进程 ...
- Requests+正则表达式抓取猫眼电影TOP100
spider.py # -*- coding:utf-8 -*- import requests import re import json import codecs from requests.e ...
- Python爬虫项目--爬取猫眼电影Top100榜
本次抓取猫眼电影Top100榜所用到的知识点: 1. python requests库 2. 正则表达式 3. csv模块 4. 多进程 正文 目标站点分析 通过对目标站点的分析, 来确定网页结构, ...
- # [爬虫Demo] pyquery+csv爬取猫眼电影top100
目录 [爬虫Demo] pyquery+csv爬取猫眼电影top100 站点分析 代码君 [爬虫Demo] pyquery+csv爬取猫眼电影top100 站点分析 https://maoyan.co ...
- 使用Request+正则抓取猫眼电影(常见问题)
目前使用Request+正则表达式,爬取猫眼电影top100的例子很多,就不再具体阐述过程! 完整代码github:https://github.com/connordb/Top-100 总结一下,容 ...
- Python爬虫【三】利用requests和正则抓取猫眼电影网上排名前100的电影
#利用requests和正则抓取猫眼电影网上排名前100的电影 import requests from requests.exceptions import RequestException imp ...
- python 爬取猫眼电影top100数据
最近有爬虫相关的需求,所以上B站找了个视频(链接在文末)看了一下,做了一个小程序出来,大体上没有修改,只是在最后的存储上,由txt换成了excel. 简要需求:爬虫爬取 猫眼电影TOP100榜单 数据 ...
随机推荐
- 获取浏览器弹窗alert、自定义弹窗以及其操作
web自动化测试第10步:获取浏览器弹窗alert.自定义弹窗以及其操作 - CSDN博客 http://blog.csdn.net/ccggaag/article/details/76573857 ...
- C语言8大经典排序算法(2)
二.插入类排序 插入排序(Insertion Sort)的基本思想是:每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的子文件中的适当位置,直到全部记录插入完成为止. 插入排序一般意义上有两 ...
- 如何调试Node.js
Debugging Node.js with Chrome DevTools https://nodejs.org/en/docs/guides/debugging-getting-started/ ...
- YTU 2623: B 抽象类-形状
2623: B 抽象类-形状 时间限制: 1 Sec 内存限制: 128 MB 提交: 235 解决: 143 题目描述 定义一个抽象类Shape, 类中有两个纯虚函数. 具体类正方形类Shape ...
- 【Silverlight】Bing Maps学习系列(五):绘制多边形(Polygon)图形(转)
[Silverlight]Bing Maps学习系列(五):绘制多边形(Polygon)图形 Bing Maps Silverlight Control支持用户自定义绘制多边形(Polygon)图形, ...
- bzoj 4337 树的同构
4337: BJOI2015 树的同构 Description 树是一种很常见的数据结构. 我们把N个点,N-1条边的连通无向图称为树. 若将某个点作为根,从根开始遍历,则其它的点都有一个前驱,这个树 ...
- POJ2749 Building road
传送门 这道题真是2-SAT好题啊!!卡了我两个点才做完……垃圾POJ还不告诉我哪错了…… 首先我们先花一段时间把题看懂……(其实是翻译一下),之后我们发现因为每个谷仓只能向一个中转点连边,所以他就是 ...
- Controller控制器的使用
如果不加@Controller注解,浏览器它是无法访问到的.@RequestMapping通过某个URL访问到我们写的方法
- 0623-TP框架整理一(下载、入口文件、路由、创建控制器、调用模板、系统常量、命名空间)
一.下载解压后用ThinkPHP(核心)文件 核心文件夹(ThinkPHP)不要改,是作用于全局的,有需要可以改应用目录(Application) 二.创建入口文件: 运行后出现欢迎界面,在说明系统自 ...
- A brief preview of the new features introduced by OpenGL 3.3 and 4.0
A brief preview of the new features introduced by OpenGL 3.3 and 4.0 The Khronos Group continues t ...