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实现方法的更多相关文章

  1. Python Spider 抓取猫眼电影TOP100

    """ 抓取猫眼电影TOP100 """ import re import time import requests from bs4 im ...

  2. Python爬虫之requests+正则表达式抓取猫眼电影top100以及瓜子二手网二手车信息(四)

    requests+正则表达式抓取猫眼电影top100 一.首先我们先分析下网页结构 可以看到第一页的URL和第二页的URL的区别在于offset的值,第一页为0,第二页为10,以此类推. 二.< ...

  3. 爬虫_python3_抓取猫眼电影top100

    使用urllib,request,和正则表达式,多线程进行秒抓,以及异常处理结果: import urllib,re,json from multiprocessing import Pool#多进程 ...

  4. Requests+正则表达式抓取猫眼电影TOP100

    spider.py # -*- coding:utf-8 -*- import requests import re import json import codecs from requests.e ...

  5. Python爬虫项目--爬取猫眼电影Top100榜

    本次抓取猫眼电影Top100榜所用到的知识点: 1. python requests库 2. 正则表达式 3. csv模块 4. 多进程 正文 目标站点分析 通过对目标站点的分析, 来确定网页结构,  ...

  6. # [爬虫Demo] pyquery+csv爬取猫眼电影top100

    目录 [爬虫Demo] pyquery+csv爬取猫眼电影top100 站点分析 代码君 [爬虫Demo] pyquery+csv爬取猫眼电影top100 站点分析 https://maoyan.co ...

  7. 使用Request+正则抓取猫眼电影(常见问题)

    目前使用Request+正则表达式,爬取猫眼电影top100的例子很多,就不再具体阐述过程! 完整代码github:https://github.com/connordb/Top-100 总结一下,容 ...

  8. Python爬虫【三】利用requests和正则抓取猫眼电影网上排名前100的电影

    #利用requests和正则抓取猫眼电影网上排名前100的电影 import requests from requests.exceptions import RequestException imp ...

  9. python 爬取猫眼电影top100数据

    最近有爬虫相关的需求,所以上B站找了个视频(链接在文末)看了一下,做了一个小程序出来,大体上没有修改,只是在最后的存储上,由txt换成了excel. 简要需求:爬虫爬取 猫眼电影TOP100榜单 数据 ...

随机推荐

  1. Windows命令实现匿名邮件发送

    在日常工具开发中,常常会有发送邮件的需求.在一些高级语言中,如Python.C#中,都有专门的邮件发送模块,如Python 中的 smtplib 模块.那么.一封邮件究竟是怎样发送到一个特定的邮箱呢? ...

  2. 【bzoj1034】[ZJOI2008]泡泡堂BNB

    贪心 将双方的选手均按从强到弱排序,然后第一次扫描尽可能用当前剩下的选手中能赢对手当前最强选手中最弱的一个去赢得胜利,若无法做到,则暂时不考虑给对方最强的选手匹配对手.第二遍扫描使用同样策略去获取尽量 ...

  3. POJ 2590:Steps

    Steps Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 7872   Accepted: 3612 Description ...

  4. searchView 颜色 icon 设置

    public void initSearchViewActions() { searchView.setMaxWidth(Integer.MAX_VALUE); searchView.onAction ...

  5. missing required source folder

    Eclipse 中XXX is missing required source folder 问题的解决 https://blog.csdn.net/itzhangdaopin/article/det ...

  6. 【USACO 2008FEB】 旅馆

    [题目链接] 点击打开链接 [算法] 线段树 对于一个节点,记录它从左端点延伸的最多的空房间的个数,从右端点延伸的最多的空房间个数,和该区间最多的连续 空房间个数 [代码] #include<b ...

  7. sqlserver新加一自增长的列,并且更新为行号

    --查询行号 select row_number()over(order by CHECKTIME )as RowNum,*from CHECKINOUT --更新id列为行号 update CHEC ...

  8. 3-4章 第3章 form表单组件与小程序前后端通信

    View它相当于是一个点击触发一个事件,但是它的事件应该是相对来说可能是比较是偏向于页面上的一些展示,或者说是页面上的一些导航的一些跳转.Button它是一个标签, button是一个标签,一般去触发 ...

  9. 如何快速删除Linux下的svn隐藏文件及其他临时文件 (转载)

    转自:http://blog.csdn.net/edsam49/article/details/5840489 在Linux下,你的代码工程如果是用svn进行管理的,要删除Linux kernel里的 ...

  10. E20171212-hm

    odd   adj. 古怪的; 奇数的; 剩余的; 临时的; odd number 奇数 even adj. 偶数的 even number 偶数