1. 创建项目
# 创建项目
django-admin startproject news
# 进入项目目录
cd news
# 创建app
python manage.py startapp app01
2. 修改 app
2.1 添加 html
- 进入 app01 文件夹
- 在 app01 文件夹中添加 templates 文件夹
- 在 templates 文件夹中添加 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新闻中心</title>
</head>
<body>
<ul>
{% for i in news_list.data.data %}
<li>{{ i.title }}</li>
{% endfor %}
</ul>
</body>
</html>
2.2 添加视图
修改views.py文件
from django.shortcuts import render
# Create your views here.
def index(req):
import requests
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.41",
}
url = "http://basic.10jqka.com.cn/basicapi/notice/news"
params = {
"type":"stock",
"code":"600050",
"current":"2",
"limit":"15",
}
res = requests.get(url=url,headers=headers,params=params)
news_list = res.json()
return render(req,"index.html",{"news_list":news_list})
3. 引用 app
3.1 修改 setting.py 文件
INSTALLED_APPS = [
...
'app01',
...
]
3.2 添加 url
修改 urls.py 文件
from app01 import views
urlpatterns = [
# path('admin/', admin.site.urls),
path('index/', views.index,
]
3. 运行项目
打开cmd窗口,进入到项目目录下,在与manage.py同级的目录下运行
python manage.py runserver
访问url:http://127.0.0.1:8000/index
标签:index,views,url,py,爬虫,Django,获取数据,app01,news From: https://www.cnblogs.com/sunhouzi/p/17732339.html