【问题标题】:Django and BeautifulSoup - Run views.py on each pageload?Django 和 BeautifulSoup - 在每个页面加载时运行 views.py?
【发布时间】:2020-05-19 19:52:07
【问题描述】:

我对 Django 完全陌生,对于这个可能非常基本的问题,我很抱歉,但我还没有想出答案。我已经在 Ubuntu 和 Virtualenv 上安装了 Django。我还安装了 BeautifulSoup 和 Requests。所以我启动了一个名为 scrape 的应用程序,并在我的 views.py 中导入了 Requests 和 BeautifulSoup

from django.shortcuts import render

import requests
from bs4 import BeautifulSoup

r = requests.get("https://www.krone.at")
soup = BeautifulSoup(r.content, 'html.parser')

headings = soup.find_all('div', {"class":"item"})
headings = headings[0: 10]

news = []

for items in headings:
    news.append(items.text.strip())


def scrape_view(request):

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

我的模板(scrape.html)如下所示:

{% extends 'base.html' %}

{% block content %}

<h2>Krone (Newsticker)</h2>

{% for item in news %}

<span class="krone headline">{{ forloop.counter }} - {{ item }}</span><br />

{% endfor %}    

{% endblock content %}

所以基本上,这工作得很好。我用 Requests 和 BeautifulSoup 抓取了一份奥地利报纸的前 10 个标题。然后我将它传递给模板并运行一个 for 循环,它给了我所有的标题。但是,当我刷新页面时,我总是会得到相同的标题,即使它们已经在我正在抓取的网站上进行了更改。当我杀死服务器并再次运行服务器时,我得到了新的头条新闻。

所以,我的问题是如何让它工作,我的 BeautifulSoup 代码在每次页面加载时执行。这样当我集成一个按钮来刷新页面时,所有标题都会更新。

非常感谢您!

【问题讨论】:

  • 将你的抓取代码放在你的视图方法中,这样每次刷新它都会抓取新数据。
  • 天哪,我就是个喇叭。非常感谢...

标签: python django beautifulsoup


【解决方案1】:

正如@Jeet 评论的那样,将 BS 逻辑移动到视图中将在每次调用视图时运行您的刮板。 views.py 中函数之外的逻辑仅在服务器重新启动时运行。

from django.shortcuts import render

import requests
from bs4 import BeautifulSoup


def scrape_view(request):

    r = requests.get("https://www.krone.at")
    soup = BeautifulSoup(r.content, 'html.parser')

    headings = soup.find_all('div', {"class":"item"})
    headings = headings[0: 10]

    news = []

    for items in headings:
        news.append(items.text.strip())

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

附:由于您正在进行网络抓取,我会考虑进行一些速率限制,以便您的应用程序不会在视图突然收到 100 个请求/秒时发送垃圾邮件https://www.krone.at。但是,这实际上取决于您的用例。

【讨论】:

  • 感谢您的回答!目前,我只是对学习 Django 以及使用 Python 和 BeautifulSoup 进行抓取感兴趣。所以这基本上是我在 Raspberry Pi 上本地运行的一个小型学习环境。到目前为止,唯一的用例是返回我每天阅读的报纸的前 10 个标题。但是,是的,对于生产站点,这肯定需要速率限制:)
猜你喜欢
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多