写这个简陋的搜索引擎主要是能让我对flask框架有一定的认识,所以我把它记录下来
一个.py主文件
# -*- coding: utf-8 -*-
from flask import Flask
from flask import render_template
from flask import request
import urllib.request
from flask_bootstrap import Bootstrap
app=Flask(__name__)
bootstrap=Bootstrap(app)
#name为当前的主文件名
def getHtml(wd,pn):
req=urllib.request.Request('https://www.baidu.com/s?wd=%s&pn=%s' %(wd,pn))
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0')
return urllib.request.urlopen(req).read()
#装饰器
@app.route('/')#定义路由
def index():
return render_template('querry.html')
@app.route('/s')
def search():
if request.method=='GET':
wd=request.args.get('wd')
wd=urllib.request.quote(wd.encode('utf-8'))
pn = request.args.get('pn')
return getHtml(wd,pn)
else:
return None
if __name__=='__main__':
app.debug=True
app.run()
一个template文件夹下的.html文件
<h1>一个搜索引擎的页面</h1>
<html>
<head>
<meta charset="utf-8">
<title>搜索界面</title>
</head>
<body bgcolor="#C0C0C0">
<form action="/s" method="get">
<input type="text" class="txt" name="wd" id="txt"/>
<button type="button" class="btn btn-success">百度一下</button>
</body>
</html>
这个html文件就是展现出来的搜索页面,如果用到css、bootstrap、js等就会有一个吸引人的页面
重要的函数实现:
# 搜索函数
@app.route('/s')
def search():
if request.method=='GET':
wd=request.args.get('wd') #因为你搜索的关键词都在wd参数中,所以用args解析得到的wd就是你搜索的词
wd=urllib.request.quote(wd.encode('utf-8'))#编码成utf-8,输入搜索词汇可以输入中文
pn = request.args.get('pn')#这里的pn参数控制搜索的页数,不加pn的话只能搜索到第一页内容
return getHtml(wd,pn)
else:
return None
# 获取访问页面
def getHtml(wd,pn):
req=urllib.request.Request('https://www.baidu.com/s?wd=%s&pn=%s' %(wd,pn))#得到两个参数之后要把相应的url读取出来
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0')#模拟浏览器访问,所以增加一个header
return urllib.request.urlopen(req).read()