【发布时间】:2019-06-04 19:09:38
【问题描述】:
0
我有一个 html 模板,其中包含一个按钮,当你按下按钮时,它会在 views.py 中执行一个函数,我将列出:
from django.shortcuts import render
from django.http import HttpResponse
import requests
from bs4 import BeautifulSoup
def button(request):
return render(request, 'home.html')
def output(request):
def trade_spider(max_pages):
dat = ''
page = 1
while(page <= max_pages):
search = 'Ipad'
url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + search + '&_sacat=0&_pgn=' + str(page)
src = requests.get(url)
text = src.text
soup = BeautifulSoup(text, features="html.parser")
for link in soup.findAll('a', {'class': 's-item__link'}):
href = link.get('href')
title = link.string
if(title == None):
title = "Sorry the title was unavailable however you can check the price."
price = get_item_price(href)
dat += href + '\n' + title + '\n' + price
page+=1
return dat
def get_item_price(item_url):
src = requests.get(item_url)
text = src.text
soup = BeautifulSoup(text, features="html.parser")
for item_price in soup.findAll('span', {'class': 'notranslate'}):
price = item_price.string
return price
data = trade_spider(1)
return render(request, 'home.html',{'data': data})
home.html:
<!DOCTYPE html>
<html>
<head>
<title>
Python button script
</title>
</head>
<body>
<button>Execute Script</button> <hr>
{% if data %}
{{data | safe}}
{% endif %}
</body>
</html>
一切正常,但是当我运行页面时,它会显示按钮和我不希望的输出,我希望它在我按下按钮后显示输出。 python 版本是 3.6.0 django=2.1 它在一个使用 pipenv 的 virtualenv 中,这就是我所拥有的所有细节。如果您需要另一个文件的代码,只需注释以防您需要该目录,并且其中的文件是一棵树:
C:.
│ Pipfile
│ Pipfile.lock
│
└───comparison
│ db.sqlite3
│ manage.py
│
├───comparison
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
└───register
│ admin.py
│ apps.py
│ models.py
│ tests.py
│ views.py
│ __init__.py
│
├───migrations
│ __init__.py
│
└───templates
home.html
views.py:
from django.contrib import admin
from django.urls import path
from register.views import output
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', output)
]
【问题讨论】:
-
那么你期待什么?您调用该函数,它会显示结果。据我所知,该按钮从未使用过。
标签: html django python-3.x