如何将请求函数视图转换为基于类的视图



我正在尝试使用我发现的这个Scraper存储库,并在Django中使用它来显示获得的数据,但我不知道如何使用基于Django类的视图,我有一个使用函数视图的小例子。使用CBV有可能做到这一点吗?

以下是片段:

from django.shortcuts import render
from bs4 import BeautifulSoup
import requests
def dj_bs(request):
if request.method == "POST":
website_link = request.POST.get('web_link', None)
#requests
url = website_link #url
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}#headers
source=requests.get(url, headers=headers).text # url source

#beautifulsoup
soup = BeautifulSoup(source, 'html.parser')
h1_val = soup.h1.string #h1 value
return render(request, 'django-bs.html', {'h1_val':h1_val})
return render(request, 'django-bs.html')
class dj_bs(View):
#runs when you hit get rquest
def get(self, request, *args, **kwargs):
context = {}
#render django-bs.html with empty context
return render(request, "django-bs.html", context=context)
#runs when you hit post method
def post(self):
website_link = self.request.POST.get('web_link', None)
# requests
url = website_link  # url
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) 
Gecko/20100101 Firefox/50.0'}  # headers
source = self.requests.get(url, headers=headers).text  # url source
# beautifulsoup
soup = BeautifulSoup(source, 'html.parser')
h1_val = soup.h1.string  # h1 value
context = {'h1_val': h1_val}
# render django-bs.html with h1_val
return render(self.request, 'django-bs.html', context=context)

你可以试试这个。

source = requests.get(url, headers=headers).content
beautify = BeautifulSoup(source.decode('utf-8', 'ignore'))
h1_val = beautify.find('h1').get_text()
return render(request, 'django-bs.html', {'h1_val':h1_val})    

相关内容

最新更新