【发布时间】: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