没有在Django中为BeautifulSoup获得任何输出

2024-10-06 06:46:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Django中尝试BeautifulSoup4,并用它解析了一个XML页面。当我尝试以不同的方式在python解释器中解析同一个XML页面时,效果很好。但在Django,我得到了如下所示的页面。在

enter image description here

在视图.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公司名称:

^{pr2}$

我做错什么了?在


Tags: django名称requesthtmlcontext公司items页面
2条回答

来自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')返回在这个tagX中找到的所有<a>标记的列表。在

模板中的item引用了bs4.element.Tag的实例,该实例是可调用的。因此Django用零参数调用item变量,这意味着它将返回item内所有元素的列表,这是无的,因为它只包含文本。因此,空白列表。在

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

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

或者,如果出于某种原因想传递实例,可以将do_not_call_in_templates属性设置为

^{pr2}$

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

不要使用:

items.title

使用:

^{pr2}$

另外,建议使用lxml进行解析。安装lxml python并使用:

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

相关问题 更多 >