详细教---用Django封装写好的模型

        本次我们要用自己写好的热销词条爬虫代码来演示如何用Django把我们写好的模型封装。

第一步:代码准备

热搜词条搜集代码:

import requests
from lxml import etree

url = "https://tophub.today/n/KqndgxeLl9"
headers={
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}

res = requests.get(
    url = url,
    headers=headers,
)

# print(res.status_code)

html = etree.HTML(res.text)
trs=html.xpath('/html/body/div[1]/div[2]/div[2]/div[1]/div[2]/div/div[1]/table/tbody/tr')

def getfirsttext(list):
    try:
        return list[0].strip()
    except:
        return ""
    
# file=open("微博热搜top50.txt",mode="w",encoding="utf-8")
for tr in trs:
    id = getfirsttext(tr.xpath('./td[1]/text()'))
    title=getfirsttext(tr.xpath('./td[2]/a/text()'))
    play=getfirsttext(tr.xpath('./td[3]/text()'))
    url=getfirsttext(tr.xpath('./td[2]/a/@href'))
    print(id,title,play,url)
#     file.write(str(id)+","+title+","+str(play))
# file.close()

第二步:创建Django项目

在你选择存放项目的文件夹中,在命令行终端中执行以下命令来创建一个新的 Django 项目,名为myproject:

django-admin startproject myproject

第三步:配置项目

        1、创建一个应用程序 myapp。

python manage.py startapp myapp

        这将在项目目录下创建一个名为 myapp 的新应用程序,其中包含应用程序的基本目录结构。

        

        2、接下来,创建一个 Django 视图,用来处理请求并将数据呈现在网页上。在你的应用程序中的 views.py 文件中编写如下代码:

        

from django.shortcuts import render
import requests
from lxml import etree

def show_hot_topics(request):
    url = "https://tophub.today/n/KqndgxeLl9"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }

    res = requests.get(url=url, headers=headers)

    html = etree.HTML(res.text)
    trs = html.xpath('/html/body/div[1]/div[2]/div[2]/div[1]/div[2]/div/div[1]/table/tbody/tr')

    hot_topics = []
    for tr in trs:
        id = getfirsttext(tr.xpath('./td[1]/text()'))
        title = getfirsttext(tr.xpath('./td[2]/a/text()'))
        play = getfirsttext(tr.xpath('./td[3]/text()'))
        url = getfirsttext(tr.xpath('./td[2]/a/@href'))
        hot_topics.append({'id': id, 'title': title, 'play': play, 'url': url})

    return render(request, 'hot_topics.html', {'hot_topics': hot_topics})

def getfirsttext(list):
    try:
        return list[0].strip()
    except:
        return ""
    

        3、创建一个模板文件,用来呈现数据。在你的应用程序中创建一个名为 templates 的文件夹,并在其中创建一个名为 hot_topics.html 的文件

     

<!-- 在 myapp/templates/hot_topics.html 文件中 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>热门话题</title>
</head>
<body>
    <h1>热门话题</h1>
    <ul>
        {% for topic in hot_topics %}
            <li>
                <a href="{{ topic.url }}">{{ topic.title }}</a> - 播放量: {{ topic.play }}
            </li>
        {% endfor %}
    </ul>
</body>
</html>

        4、配置 URL 路由,使得当用户访问特定的 URL 时能够触发 show_hot_topics 视图。在你的应用程序中的 urls.py 文件中编写如下代码:

       

from django.urls import path
from .views import show_hot_topics

urlpatterns = [
    path('hot-topics/', show_hot_topics, name='hot_topics'),
]

        5、在myproject下的setting.py,设置模板路径

# settings.py

TEMPLATES = [
    {
        ...
        'DIRS': [BASE_DIR / 'myapp' / 'templates'], # 设置模板文件路径
        ...
    }
]

        6、在myproject下的urls.py,添加URL配置

        path('api/', include('myapp.urls')),            myapp.urls就是指自己的模块文件

'api/'的话,需要http://127.0.0.1:8000/api/hot-topics/    这样去访问。

如果‘’的话,则直接http://127.0.0.1:8000/hot-topics/

# myproject/urls.py

from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),  # 包含应用程序的 URL 配置
]

第四步:启动开发服务器

进入刚刚创建的 myproject 目录,并执行以下命令以启动开发服务器:

cd myproject
python manage.py runserver

输入网址http://127.0.0.1:8000/api/hot-topics/

注意,这个url格式有加密,所以访问不了很正常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值