jquery ajax flask 前后端通讯
如题,以自己的博客为例,抓取博客信息,一个api后台服务提供数据,前端服务接收数据并展示
目录结构:
test
|——app
|----\_\_init\_\_.py
|----flaskapp.py(后台服务)
|——blogtest
|----index.html(首页)
|----gettitle.html(标题页)
|----getmian.html(内容页)
|——get_pagenum.py(页码抓取)
|——get_title.py(标题抓取)
|——get_main.py(内容抓取)
|——rest_response.py(返回信息处理)
代码:
抓取部分:
get_pagenum.py:
# -*- coding: utf-8 -*-
#__author__="ZJL"
import requests
from lxml import etree
class GetPageNum(object):
def __init__(self):
self.session = requests.session()
self.headers = {
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch",
"Accept-Language": "zh-CN,zh;q=0.8",
}
def get_pagenum(self,resp):
url = "http://blog.csdn.net/u013055678?viewmode=contents"
r = self.session.get(url, headers=self.headers, timeout=30)
html_bodys = etree.HTML(r.content)
pagenum = html_bodys.xpath('//*[@id="papelist"]/span/text()')
if pagenum:
pagenum = pagenum[0].split("共")[1].split("页")[0]
resp.success(pagenum)
get_title.py:
# -*- coding: utf-8 -*-
#__author__="ZJL"
import requests
from lxml import etree
# from rest_response import RestResponse
class TitleGet(object):
def __init__(self):
self.session = requests.session()
self.headers = {
"Upgrade-Insecure-Requests":"1",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding":"gzip, deflate, sdch",
"Accept-Language":"zh-CN,zh;q=0.8",
}
def get_title(self,pagenum,resp):
data_list=[]
url = "http://blog.csdn.net/u013055678/article/list/"+str(pagenum)
r = self.session.get(url,headers=self.headers,timeout=30)
html_bodys = etree.HTML(r.content)
title_urls = html_bodys.xpath("//span[@class='link_title']/a")
if title_urls:
for title_url in title_urls:
data_dict = {}
url = title_url.xpath("@href")
titletext = title_url.xpath("text()")
if not url and titletext:
continue
url = "http://blog.csdn.net" + url[0].strip()
titletext = titletext[0].strip()
data_dict["url"] = url
data_dict["title"] = titletext
data_list.append(data_dict)
return resp.success(data_list)
get_main.py:
# -*- coding: utf-8 -*-
#__author__="ZJL"
import requests
from lxml import etree
import html
class GetMain(object):
def __init__(self):
self.session = requests.session()
self.headers = {
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch",
"Accept-Language": "zh-CN,zh;q=0.8",
}
def get_main(self,url,resp):
r = self.session.get(url, headers=self.headers, timeout=30)
html_bodys = etree.HTML(r.text)
# tree = lxml.html.fromstring(r.text)
# tree = lxml.html.tostring(r.text)
bodys = html_bodys.xpath('//*[@id="article_content"]')
# print((etree.tostring(bodys[0],pretty_print=True)).decode())
html_parser = html.unescape((etree.tostring(bodys[0],pretty_print=True)).decode())
return resp.success(html_parser)
rest_response.py:
# -*- coding: utf-8 -*-
import time
import json
class RestResponse(object):
"""
REST请求统一格式返回类,负责返回数据的格式
"""
def __init__(self):
self.errCode = 0
self.errMsg = ""
self.acceptAt = time.time() * 1000
self.duration = 0
self.data = {}
def success(self, data):
self.data = data
def error(self, error):
self.errCode = error[0]
self.errMsg = error[1]
def get_json(self):
self.duration = time.time() * 1000 - self.acceptAt
return json.dumps(
{"errCode": self.errCode, "errMsg": self.errMsg, "acceptAt": self.acceptAt, "duration": self.duration,
"data": self.data}, ensure_ascii=False)
后台服务代码:
flaskapp.py:
# -*- coding: utf-8 -*-
#__author__="ZJL"
from flask import Flask
from flask import request
from flask import Response
from get_title import TitleGet
from get_main import GetMain
from get_pagenum import GetPageNum
from rest_response import RestResponse
import json
app = Flask(__name__)
def Response_headers(content):
resp = Response(content)
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
@app.route('/')
def hello_world():
return Response_headers('hello world')
@app.route('/findTitleList', methods=['POST'])
def findTitleList():
if request.method == 'POST' and request.form['pagenum']:
datax = request.form
print(datax)
# print("zzzzzzzzzz",type(datax))
# print("aaaaaaaaaaa",dict(datax))
# print("zzzzzzzzzz", datax)
pagenum = request.form['pagenum']
tg = TitleGet()
resp = RestResponse()
tg.get_title(pagenum,resp)
content = resp.get_json()
resp = Response_headers(content)
return resp
else:
content = json.dumps({"error_code":"1001"})
resp = Response_headers(content)
return resp
@app.route('/findMain', methods=['POST'])
def findMain():
if request.method == 'POST' and request.form['url']:
url = request.form['url']
gm = GetMain()
resp = RestResponse()
gm.get_main(url,resp)
content = resp.get_json()
content = content
resp = Response_headers(content)
return resp
else:
content = json.dumps({"error_code": "2001"})
resp = Response_headers(content)
return resp
@app.route('/getPagenum', methods=['POST'])
def getPagenum():
if request.method == 'POST':
resp = RestResponse()
gn = GetPageNum()
gn.get_pagenum(resp)
content = resp.get_json()
resp = Response_headers(content)
return resp
else:
content = json.dumps({"error_code": "3001"})
resp = Response_headers(content)
return resp
@app.errorhandler(403)
def page_not_found(error):
content = json.dumps({"error_code": "403"})
resp = Response_headers(content)
return resp
@app.errorhandler(404)
def page_not_found(error):
content = json.dumps({"error_code": "404"})
resp = Response_headers(content)
return resp
@app.errorhandler(400)
def page_not_found(error):
content = json.dumps({"error_code": "400"})
resp = Response_headers(content)
return resp
@app.errorhandler(410)
def page_not_found(error):
content = json.dumps({"error_code": "410"})
resp = Response_headers(content)
return resp
@app.errorhandler(500)
def page_not_found(error):
content = json.dumps({"error_code": "500"})
resp = Response_headers(content)
return resp
if __name__ == '__main__':
app.run(debug=True)#threaded=True,
前端服务:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body οnlοad="load()">
<h3>我的blog</h3>
<ul></ul>
</body>
<script>
function load(){
$.ajax({
url:'http://127.0.0.1:5000/getPagenum',
type:'post', //数据发送方式
dataType:'json', //接受数据格式 (这里有很多,常用的有html,xml,js,json)
// data:'pagenum=1', //要传递的数据
error: function(){ //失败
alert('Error loading document');
},
success: function(msg){ //成功
var num = parseInt(msg["data"])
for(var i=1;i<num+1;i++){
$("ul").append($("<li><a href='' id='a"+i+"'>"+i+"</a></li>"));
$('#a'+i).attr('href',"gettitle.html?num="+i);
}
}
});
};
</script>
</html>
gettitle.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>aaaa</title>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body οnlοad="load()">
<a href="index.html">rturn</a>
<ul>
</ul>
</body>
<script>
var num;
var thisURL = document.URL;
// alert(thisURL);
// alert(thisURL.indexOf("index"));
if(thisURL.indexOf("gettitle")>0){
var getval =thisURL.split("?")[1];
num = getval.split("=")[1];
// alert("aaa"+num);
}else{
num="1";
}
// alert(num)
function load(){
$.ajax({
url:'http://127.0.0.1:5000/findTitleList',
type:'post', //数据发送方式
dataType:'json', //接受数据格式 (这里有很多,常用的有html,xml,js,json)
data:'pagenum='+num, //要传递的数据
error: function(){ //失败
alert('Error loading document');
},
success: function(msg){ //成功
for(var i=0;i<msg["data"].length;i++){
$("ul").append($("<li><a href='' id='a"+i+"'>"+msg["data"][i]["title"]+"</a></li>"));
$('#a'+i).attr('href',"getmian.html?url="+msg["data"][i]["url"]);
}
}
});
};
</script>
</html>
getmian.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body οnlοad="load()">
<a href="gettitle.html">rturn</a>
<div id="blog_main"></div>
</body>
<script>
var thisURL = document.URL;
var getval =thisURL.split("?")[1];
var url = getval.split("=")[1];
// var url = "http://blog.csdn.net/u013055678/article/details/54172693";
function load(){
$.ajax({
url:'http://127.0.0.1:5000/findMain',
type:'post', //数据发送方式
dataType:'json', //接受数据格式 (这里有很多,常用的有html,xml,js,json)
data:'url='+url, //要传递的数据
error: function(){ //失败
alert('Error loading document');
},
success: function(msg){ //成功
$("#blog_main").html(msg["data"]);
}
});
};
</script>
</html>
还没有评论,来说两句吧...