Python爬虫学习记录(0)——flask入门
从这里将开始我的python爬虫学习之旅,并且记录学习过程,不定期更新。
先引入的是flask的首个程序hello word!
Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活、轻便、安全且容易上手。它可以很好地结合MVC模式进行开发,开发人员分工合作,小型团队在短时间内就可以完成功能丰富的中小型网站或Web服务的实现。另外,Flask还有很强的定制性,用户可以根据自己的需求来添加相应的功能,在保持核心功能简单的同时实现功能的丰富与扩展,其强大的插件库可以让用户实现个性化的网站定制,开发出功能强大的网站。摘自百度百科
1.首先导入flask库:没有的话可以尝试命令行(cmd)pip install flask进行安装库文件
import flask
2.初始化一个flask对象:
app = flask.Flask(__name__)
3.设置路由函数
@app.route("/")#设置为根目录
def index():
try:
file = open("index.html","rb")#打开index.html文件
data = file.read()#读取到给data
file.close()#关闭文件
return data#将内容返回给客户端
except Exception as e:
return str(e)
4.定义主函数:
def main():
app.run()
5.运行服务器:
main()
下面是完整代码:
import flask
app = flask.Flask(__name__)
@app.route("/")
def index():
try:
file= open("index.html","rb")
data = file.read()
file.close()
return data
except Exception as e:
return str(e)
def main():
app.run()
main()
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>hello world!</h1>
</body>
</html>
然后就可以运行了:运行成功--》
* Serving Flask app "FlaskServer" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [01/May/2020 10:34:06] "GET / HTTP/1.1" 200 -
使用浏览器打开http://127.0.0.1:5000
就可以看到界面:
到此,服务器完成。
下面通过python获取网页信息爬取:在这里使用urllib的request方法
导入request库:
import urllib.request
设置url:
url = "http://127.0.0.1:5000"
获取网页内容:
html = urllib.request.urlopen(url)
读取数据:
data = html.read()
处理编码:
data = data.decode()
然后就是print:
print(data)
下面是全部client代码:
import urllib.request
url = "http://127.0.0.1:5000"
html = urllib.request.urlopen(url)
data = html.read()
data = data.decode()
print(data)
运行服务器,然后运行client:控制台输出以下内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>hello world!</h1>
</body>
</html>
目录结构:
本节到此结束!
记录学习过程。