概述
爬虫是合法的吗?
是的,它是一个计算机的学科!一个工具
什么是爬虫?
通过编写程序,模拟 浏览器上网,然后让其去互联网上爬取 /获取数据的过程.爬虫爬取的也就是服务端的响应数据
爬虫使用场景的分类
- 通用爬虫 : 爬取一整张页面数据."抓取系统"
- 聚焦爬虫 : 爬取页面中指定的内容,建立在通用爬虫的基础上,爬到数据后,进行局部数据解析筛选
- 增量式爬虫 : 用来检测 网站数据更新的情况.只爬取网站最新更新的数据.
反扒机制
网站指定了相关的技术手段或者策略阻止爬虫程序进行网页数据的爬取
- 机制一 : robots协议:一个文本协议,防君子不防小人的协议(哈哈),只是让你主观遵从,但也可以忽略直接爬取!
- 机制二 : UA检测,检测请求载体是否基于某一款浏览器
反反扒策略
爬虫破解网站指定的反扒策略
机制一 : 直接忽略
机制二 : UA伪装
http/https协议
客户端和服务器端进行数据交互 的一种形式
- 请求头信息 :
- User-Agent : 请求载体身份标识
- Connection : close (请求成功后马上断开)
- 响应头信息
-Content-Type : json...
- https : 安全
- 加密方式 :
- 对称秘钥加密 : 浏览器将秘钥和密文一起发送给服务器,极度不安全
- 非对称秘钥加密 : 客户端没有保障秘钥是服务器发送的,可能被拦截替换,也不安全
- 证书秘钥加密 : 安全
Jupyter
编写爬虫程序的环境
编写程序
什么是动态加载的数据?
页面加载的时候,通过ajax提交的post数据.
相关模块
-urllib # 比较古老,用法繁琐被requests模块代替
requests:网络请求的一个模块. requests的作用: 模拟浏览器发请求。进而实现爬虫 requests的编码流程: - 1.指定url - 2.发起请求 - 3.获取响应数据 - 4.持久化存储
示例1 搜狗首页页面数据
# 简单通用爬虫
import requests
# 指定url
url = " https://www.sougou.com/ "
# 发起请求:get的返回值就是一个响应对象
response = requests.get(url=url)
# 获取响应数据,返回字符串形式的响应数据
page_text = response.text
# 持久化存储
with open(" ./sougou.html " ," w " ,encoding=" utf-8 " ) as fp:
fp.write(page_text)
示例2 爬取搜狗自定词条搜索后的页面数据
import requests
url = " https://www.sogou.com/web "
content = input(" >>> " ).strip()
param = {" query " :content}
headers = {
" User-Agent " :" Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36 "
}
response = requests.get(url=url,params=param,headers = headers)
response.encoding = " utf-8 "
page_text = response.text
name = content + " .html "
with open(name, ' w ' ,encoding=" utf-8 " ) as f:
f.write(page_text)
print (" 爬取成功 " )
示例3 破解百度翻译
# 破解百度翻译爬取想要的信息 动态加载数据,
import requests
content = input(" 输入一个单词: " )
url = " https://fanyi.baidu.com/sug "
headers = {
" User-Agent " :" Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36 "
}
data = {" kw " :content}
response = requests.post(url=url,headers=headers,data=data)
obj_json = response.json()
print (obj_json)
示例4 爬取豆瓣电影中的电影详情数据
# 爬取豆瓣上的电影,注意,页面上可能存在动态页面
import requests,json
url = " https://movie.douban.com/j/chart/top_list "
headers = {
" User-Agent " :" Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36 "
}
param = {
" type " : " 5 " ,
" interval_id " : " 100:90 " ,
" action " : "" ,
" start " : " 0 " ,
" limit " : " 200 "
}
response = requests.get(url=url,params=param,headers=headers)
movie_json = response.json()
name = " dz_movie " +" .json "
print (len(movie_json))
with open(name, " w " ,encoding=" utf-8 " ) as f:
json.dump(movie_json,f)
print (" 爬取写入完成 " )
示例5 爬取任意城市肯德基的餐厅位置信息
import requests,json
all_data = []
url = " http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword "
content = input(" 请输入城市名称: " ).strip()
headers = {
" User-Agent " :" Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36 "
}
for i in range(1,8):
data = {
" cname " :"" ,
" pid " : "" ,
" keyword " : content,
" pageIndex " : str(i),
" pageSize " : " 10 "
}
json_obj = requests.post(url=url,headers=headers,data=data).json()
for i in json_obj[' Table1 ' ]:
all_data.append(i)
name = ' KFC.json '
with open (name, " w " ,encoding=" utf-8 " )as f:
json.dump(all_data,f)
print (" KFC data is ok " )
爬取KFC门店
示例6.化妆品企业
# 查看国家药监总局中基于中华人民共和国化妆品生产许可证相关数据
import requests,json
id_lst = [] # 获取所有企业UUID
all_data = [] # 存储所有企业的详情信息
post_url = " http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsList "
headers = {
" User-Agent " :" Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36 "
}
for i in range(1,10):
data = {
" on " : " true " ,
" page " : str(i),
" pageSize " : " 15 " ,
" productName " : "" ,
" conditionType " : " 1 " ,
" applyname " : "" ,
" applysn " : ""
}
json_obj = requests.post(url=post_url,headers=headers,data=data).json()
for dic in json_obj[" list " ]:
ID = dic[" ID " ]
id_lst.append(ID)
for id in id_lst:
detail_post_url = " http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsById "
data = {" id " :id}
detail_dic = requests.post(url=detail_post_url,data=data).json()
all_data.append(detail_dic)
name = " hzpqy " +" .json "
with open(name, " w " ,encoding=" utf-8 " ) as fb:
json.dump(all_data,fb)
print (" data is ok! " )
爬取化妆品企业信息
...
CrazyShenldon
posted @
2019-04-30 12:36
FindSoul
阅读(
892 )
评论()
收藏
举报
var RENDERER = {
POINT_INTERVAL : 5,
FISH_COUNT : 3,
MAX_INTERVAL_COUNT : 50,
INIT_HEIGHT_RATE : 0.5,
THRESHOLD : 50,
init : function(){
this.setParameters();
this.reconstructMethods();
this.setup();
this.bindEvent();
this.render();
},
setParameters : function(){
this.$window = $(window);
this.$container = $('#jsi-flying-fish-container');
this.$canvas = $(' ');
this.context = this.$canvas.appendTo(this.$container).get(0).getContext('2d');
this.points = [];
this.fishes = [];
this.watchIds = [];
},
createSurfacePoints : function(){
var count = Math.round(this.width / this.POINT_INTERVAL);
this.pointInterval = this.width / (count - 1);
this.points.push(new SURFACE_POINT(this, 0));
for(var i = 1; i < count; i++){
var point = new SURFACE_POINT(this, i * this.pointInterval),
previous = this.points[i - 1];
point.setPreviousPoint(previous);
previous.setNextPoint(point);
this.points.push(point);
}
},
reconstructMethods : function(){
this.watchWindowSize = this.watchWindowSize.bind(this);
this.jdugeToStopResize = this.jdugeToStopResize.bind(this);
this.startEpicenter = this.startEpicenter.bind(this);
this.moveEpicenter = this.moveEpicenter.bind(this);
this.reverseVertical = this.reverseVertical.bind(this);
this.render = this.render.bind(this);
},
setup : function(){
this.points.length = 0;
this.fishes.length = 0;
this.watchIds.length = 0;
this.intervalCount = this.MAX_INTERVAL_COUNT;
this.width = this.$container.width();
this.height = this.$container.height();
this.fishCount = this.FISH_COUNT * this.width / 500 * this.height / 500;
this.$canvas.attr({width : this.width, height : this.height});
this.reverse = false;
this.fishes.push(new FISH(this));
this.createSurfacePoints();
},
watchWindowSize : function(){
this.clearTimer();
this.tmpWidth = this.$window.width();
this.tmpHeight = this.$window.height();
this.watchIds.push(setTimeout(this.jdugeToStopResize, this.WATCH_INTERVAL));
},
clearTimer : function(){
while(this.watchIds.length > 0){
clearTimeout(this.watchIds.pop());
}
},
jdugeToStopResize : function(){
var width = this.$window.width(),
height = this.$window.height(),
stopped = (width == this.tmpWidth && height == this.tmpHeight);
this.tmpWidth = width;
this.tmpHeight = height;
if(stopped){
this.setup();
}
},
bindEvent : function(){
this.$window.on('resize', this.watchWindowSize);
this.$container.on('mouseenter', this.startEpicenter);
this.$container.on('mousemove', this.moveEpicenter);
this.$container.on('click', this.reverseVertical);
},
getAxis : function(event){
var offset = this.$container.offset();
return {
x : event.clientX - offset.left + this.$window.scrollLeft(),
y : event.clientY - offset.top + this.$window.scrollTop()
};
},
startEpicenter : function(event){
this.axis = this.getAxis(event);
},
moveEpicenter : function(event){
var axis = this.getAxis(event);
if(!this.axis){
this.axis = axis;
}
this.generateEpicenter(axis.x, axis.y, axis.y - this.axis.y);
this.axis = axis;
},
generateEpicenter : function(x, y, velocity){
if(y < this.height / 2 - this.THRESHOLD || y > this.height / 2 + this.THRESHOLD){
return;
}
var index = Math.round(x / this.pointInterval);
if(index < 0 || index >= this.points.length){
return;
}
this.points[index].interfere(y, velocity);
},
reverseVertical : function(){
this.reverse = !this.reverse;
for(var i = 0, count = this.fishes.length; i < count; i++){
this.fishes[i].reverseVertical();
}
},
controlStatus : function(){
for(var i = 0, count = this.points.length; i < count; i++){
this.points[i].updateSelf();
}
for(var i = 0, count = this.points.length; i < count; i++){
this.points[i].updateNeighbors();
}
if(this.fishes.length < this.fishCount){
if(--this.intervalCount == 0){
this.intervalCount = this.MAX_INTERVAL_COUNT;
this.fishes.push(new FISH(this));
}
}
},
render : function(){
requestAnimationFrame(this.render);
this.controlStatus();
this.context.clearRect(0, 0, this.width, this.height);
this.context.fillStyle = 'hsl(0, 0%, 95%)';
for(var i = 0, count = this.fishes.length; i < count; i++){
this.fishes[i].render(this.context);
}
this.context.save();
this.context.globalCompositeOperation = 'xor';
this.context.beginPath();
this.context.moveTo(0, this.reverse ? 0 : this.height);
for(var i = 0, count = this.points.length; i < count; i++){
this.points[i].render(this.context);
}
this.context.lineTo(this.width, this.reverse ? 0 : this.height);
this.context.closePath();
this.context.fill();
this.context.restore();
}
};
var SURFACE_POINT = function(renderer, x){
this.renderer = renderer;
this.x = x;
this.init();
};
SURFACE_POINT.prototype = {
SPRING_CONSTANT : 0.03,
SPRING_FRICTION : 0.9,
WAVE_SPREAD : 0.3,
ACCELARATION_RATE : 0.01,
init : function(){
this.initHeight = this.renderer.height * this.renderer.INIT_HEIGHT_RATE;
this.height = this.initHeight;
this.fy = 0;
this.force = {previous : 0, next : 0};
},
setPreviousPoint : function(previous){
this.previous = previous;
},
setNextPoint : function(next){
this.next = next;
},
interfere : function(y, velocity){
this.fy = this.renderer.height * this.ACCELARATION_RATE * ((this.renderer.height - this.height - y) >= 0 ? -1 : 1) * Math.abs(velocity);
},
updateSelf : function(){
this.fy += this.SPRING_CONSTANT * (this.initHeight - this.height);
this.fy *= this.SPRING_FRICTION;
this.height += this.fy;
},
updateNeighbors : function(){
if(this.previous){
this.force.previous = this.WAVE_SPREAD * (this.height - this.previous.height);
}
if(this.next){
this.force.next = this.WAVE_SPREAD * (this.height - this.next.height);
}
},
render : function(context){
if(this.previous){
this.previous.height += this.force.previous;
this.previous.fy += this.force.previous;
}
if(this.next){
this.next.height += this.force.next;
this.next.fy += this.force.next;
}
context.lineTo(this.x, this.renderer.height - this.height);
}
};
var FISH = function(renderer){
this.renderer = renderer;
this.init();
};
FISH.prototype = {
GRAVITY : 0.4,
init : function(){
this.direction = Math.random() < 0.5;
this.x = this.direction ? (this.renderer.width + this.renderer.THRESHOLD) : -this.renderer.THRESHOLD;
this.previousY = this.y;
this.vx = this.getRandomValue(4, 10) * (this.direction ? -1 : 1);
if(this.renderer.reverse){
this.y = this.getRandomValue(this.renderer.height * 1 / 10, this.renderer.height * 4 / 10);
this.vy = this.getRandomValue(2, 5);
this.ay = this.getRandomValue(0.05, 0.2);
}else{
this.y = this.getRandomValue(this.renderer.height * 6 / 10, this.renderer.height * 9 / 10);
this.vy = this.getRandomValue(-5, -2);
this.ay = this.getRandomValue(-0.2, -0.05);
}
this.isOut = false;
this.theta = 0;
this.phi = 0;
},
getRandomValue : function(min, max){
return min + (max - min) * Math.random();
},
reverseVertical : function(){
this.isOut = !this.isOut;
this.ay *= -1;
},
controlStatus : function(context){
this.previousY = this.y;
this.x += this.vx;
this.y += this.vy;
this.vy += this.ay;
if(this.renderer.reverse){
if(this.y > this.renderer.height * this.renderer.INIT_HEIGHT_RATE){
this.vy -= this.GRAVITY;
this.isOut = true;
}else{
if(this.isOut){
this.ay = this.getRandomValue(0.05, 0.2);
}
this.isOut = false;
}
}else{
if(this.y < this.renderer.height * this.renderer.INIT_HEIGHT_RATE){
this.vy += this.GRAVITY;
this.isOut = true;
}else{
if(this.isOut){
this.ay = this.getRandomValue(-0.2, -0.05);
}
this.isOut = false;
}
}
if(!this.isOut){
this.theta += Math.PI / 20;
this.theta %= Math.PI * 2;
this.phi += Math.PI / 30;
this.phi %= Math.PI * 2;
}
this.renderer.generateEpicenter(this.x + (this.direction ? -1 : 1) * this.renderer.THRESHOLD, this.y, this.y - this.previousY);
if(this.vx > 0 && this.x > this.renderer.width + this.renderer.THRESHOLD || this.vx < 0 && this.x < -this.renderer.THRESHOLD){
this.init();
}
},
render : function(context){
context.save();
context.translate(this.x, this.y);
context.rotate(Math.PI + Math.atan2(this.vy, this.vx));
context.scale(1, this.direction ? 1 : -1);
context.beginPath();
context.moveTo(-30, 0);
context.bezierCurveTo(-20, 15, 15, 10, 40, 0);
context.bezierCurveTo(15, -10, -20, -15, -30, 0);
context.fill();
context.save();
context.translate(40, 0);
context.scale(0.9 + 0.2 * Math.sin(this.theta), 1);
context.beginPath();
context.moveTo(0, 0);
context.quadraticCurveTo(5, 10, 20, 8);
context.quadraticCurveTo(12, 5, 10, 0);
context.quadraticCurveTo(12, -5, 20, -8);
context.quadraticCurveTo(5, -10, 0, 0);
context.fill();
context.restore();
context.save();
context.translate(-3, 0);
context.rotate((Math.PI / 3 + Math.PI / 10 * Math.sin(this.phi)) * (this.renderer.reverse ? -1 : 1));
context.beginPath();
if(this.renderer.reverse){
context.moveTo(5, 0);
context.bezierCurveTo(10, 10, 10, 30, 0, 40);
context.bezierCurveTo(-12, 25, -8, 10, 0, 0);
}else{
context.moveTo(-5, 0);
context.bezierCurveTo(-10, -10, -10, -30, 0, -40);
context.bezierCurveTo(12, -25, 8, -10, 0, 0);
}
context.closePath();
context.fill();
context.restore();
context.restore();
this.controlStatus(context);
}
};
$(function(){
RENDERER.init();
});