BeautifulSoup 在 Django 中没有得到任何输出

Not getting any output in Django for BeautifulSoup

我正在 Django 中尝试 BeautifulSoup4,我用它解析了一个 XML 页面。当我尝试以不同的方式在 python 解释器中解析相同的 XML 页面时,它工作正常。但在 Django 中,我得到如下所示的页面。

views.py:

def rssfeed(request):
    list1=[]
    xmllink="https://rss.sciencedaily.com/computers_math/computer_programming.xml"
    soup=BeautifulSoup(urlopen(xmllink),'xml')
    for items in soup.find_all('item'):
        list1.append(items.title)
    context={
        "list1":list1
    }
    return render(request,'poll/rssfeed.html',context)

rssfeed.html:

{% if list1 %}

<ul>
    {% for item in list1 %}
        <li>{{ item }}</li>
    {% endfor %}
</ul>
{% endif %}

我做错了什么?

来自documentation

If any part of the variable is callable, the template system will try calling it.

Occasionally you may want to turn off this feature for other reasons, and tell the template system to leave a variable uncalled no matter what. To do so, set a do_not_call_in_templates attribute on the callable with the value True.

BeautifulSoup documentation

Calling a tag is like calling find_all()

例如。 tagX('a') return 是在此 tagX.

中找到的所有 <a> 标签的列表

您模板中的item指的是bs4.element.Tag的实例,它是可调用的。所以 Django 使用零参数调用 item 变量,这意味着它将 return 列出 item 中的所有元素,这是 none 因为它只包含文本。因此空白列表。

因此要么在将上下文传递给模板之前解析上下文

list1 = [item.title.text for item in soup.find_all('item')]

或者如果你因为某些原因想要传递实例,你可以将do_not_call_in_templates属性设置为to

for item in soup.find_all('item'):
    title = item.title
    title.do_not_call_in_templates = True
    list1.append(title)

要从 XML 获取文本,您需要调用 get_text() 函数。

不要使用:

items.title

使用:

items.title.get_text()

另外,推荐使用lxml解析。安装 lxml python 并使用:

soup = BeautifulSoup(urlopen(xmllink), 'lxml-xml')