for循环在Python中有效,但在Django中无效

时间:2020-04-02 12:33:35

标签: python django beautifulsoup

我需要从站点解析h2标签。 我用BeautifulSoup

这是Views.py的一部分。我搜索所有H2标签

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests

def index(request):
    if request.method == "POST":
        url = request.POST.get('web_link', None)
        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
        #bs
        soup = BeautifulSoup(source, 'html.parser')


        # Title INFO
        title_num = soup.find_all('title')
        title_num = len(title_num)
        title = soup.title.text
        title_len = len(title)


        # H1 INFO
        h1_num = soup.find_all('h1')
        h1_num = len(h1_num)
        h1 = soup.h1.text

        # H2 INFO
        h2_all = soup.find_all('h2')
        h2_num = len(h2_all)

        return render(request, 'tags/django-bs.html', {
            'title':title,
            'title_len':title_len,
            'title_num':title_num,
            'h1_num':h1_num,
            'h1':h1,
            'h2_all':h2_all,
            'h2_num':h2_num,
            'h21':h21
            })

    return render(request, 'tags/django-bs.html')

这是模板部分:

<h2>H2 info</h2>
      <table class="table">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">Test</th>
            <th scope="col">Value</th>
            <th scope="col">Result</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th scope="row">1</th>
            <td>H2 quantity:</td>
            <td>{{ h2_num }}</td>
            <td>None</td>
          </tr>
          <tr>
            <th scope="row">3</th>
            <td>H2</td>
            <td>{{ h2_all }}</td>
            <td>None</td>
          </tr>
          <tr>
            <th scope="row">3</th>
            <td>H2 tags:</td>
            <td>
              {% for h2 in h2_all %}
                {{ h2 }}
              {% endfor %}
            </td>
            <td>E</td>
          </tr>
        </tbody>
      </table>

在模板部分。 当我尝试显示h2_all时,它可以工作。结果是: [<h2>Запись к врачу</h2>, <h2>Запись на диагностику</h2>]

但是当我试图循环获取每个h2标签时。

{% for h2 in h2_all %}
  {{ h2 }}
{% endfor %}

结果如下:[] []

我是一个初学者,这是我在Django上的第一个项目。我已经花了几个小时尝试解决问题,但是没有结果... 请帮助...

2 个答案:

答案 0 :(得分:0)

尝试一下:

{% for h2t in h2_all.get_text %}
  <h2>{{ h2t }}</h2>
{% endfor %}

如果h2_all只有1个项目,则for循环将不起作用

您在h2_all中获得了多少个物品?

答案 1 :(得分:0)

您是否要在将BeautifulSoup标签传递给视图之前将其转换为字符串?

您可以使用类似这样的内容:

# H2 INFO
h2_all = soup.find_all('h2')
h2_all = [h.text for h in h2_all]

这是必需的,因为find_all()方法返回了<class 'bs4.element.Tag'>对象,这些对象无法在Django模板中表示。