前言
大家好,这是我第一个作品,做的不好的地方请多多指教~
目录
正片
python部分——导库(布局不说了)
from flask import* #flask是一个库,可以用来搭建服务器~
python部分——获取路由
app=Flask(__name__) #注意是左右各两个下划线
@app.route("/") #如果网址是"/",默认为http://127.0.0.1:5000/
python部分——定义返回函数
flask的路由和函数一一对应
#这里我喜欢用index()
def index():
a=get_news()
#这里后面会讲,是我自己封装的库,可以获取百度的热搜并返回字典,键是标题,值是网址
return render_template("index.html",news=a)
#很重要,index.html必须装在templates文件夹下面;news是变量,必须有赋值过程
python部分——常开服务器
app.run() #这里不要手贱加参数
爬虫——get_news()解读
#函数名称和参数数量必须与前面保持一致
def get_news():
import requests #导库不说了
import bs4
response = requests.get("https://top.baidu.com/board?tab=realtime")
soup = bs4.BeautifulSoup(response.text, "lxml")
data = soup.find_all(name="a", class_="title_dIF3B")
da=soup.find_all(name="a",class_="img-wrapper_29V76")
#爬虫区
#————————————————分————界————线——————————————————
#算法区
l1=[]
l2=[]
d={}
try:
#典型的给字典添加元素
for n in data:
l1.append(n.text)
for n1 in da:
l2.append(n1["href"])
for i in range(max(len(l1),len(l2))):
d[l1[i]]=l2[i]
return d
except:
return "获取失败"
python完整代码
现在,每个模块的代码我们已经搞定了。
我们要合并所有代码才能完成服务器和实时热点的python部分。
from flask import*
def get_news():
import requests
import bs4
response = requests.get("https://top.baidu.com/board?tab=realtime")
soup = bs4.BeautifulSoup(response.text, "lxml")
data = soup.find_all(name="a", class_="title_dIF3B")
da=soup.find_all(name="a",class_="img-wrapper_29V76")
l1=[]
l2=[]
d={}
try:
for n in data:
l1.append(n.text)
for n1 in da:
l2.append(n1["href"])
for i in range(max(len(l1),len(l2))):
d[l1[i]]=l2[i]
return d
except:
return "获取失败"
app=Flask(__name__)
@app.route("/")
def index():
d=get_news()
return render_template("index.html",news=d)
app.run()
HTML部分——接受和遍历
在python中,我们已经传输了数据。
现在,我们需要在HTML中接收数据
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
{% for i in news %}
<!--HTML循环有三部分:头,尾,主体。其中头尾要用{%%}包起来-->
<p><a href = "{{news[i]}}">{{i}}</a></p>
<!--主体可以自由发挥,主要是1.得明白键和值分别是链接还是标题;2.如果是可变的记得加{{}}-->
{% endfor %}
<!--和python不同的是,HTML遍历有循环尾-->
</body>
</html>
这里其实所不缩进都无所谓的,主要是HTML文件名必须和python的render_template()第一个参数名保持一致,并且在templates文件夹下面
结束语
好了,本期教程就结束了。作者是中学生,有些地方做的不太好,请谅解。
再次感谢观众老爷们观看!