我在Django中尝试BeautifulSoup4,并用它解析了一个XML页面。当我尝试以不同的方式在python解释器中解析同一个XML页面时,效果很好。但在Django,我得到了如下所示的页面。在
在视图.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}$我做错什么了?在
来自documentation
以及
从BeautifulSoup documentation
例如,
tagX('a')
返回在这个tagX
中找到的所有<a>
标记的列表。在模板中的
item
引用了bs4.element.Tag
的实例,该实例是可调用的。因此Django用零参数调用item
变量,这意味着它将返回item
内所有元素的列表,这是无的,因为它只包含文本。因此,空白列表。在因此,要么在将上下文传递给模板之前解析它
或者,如果出于某种原因想传递实例,可以将
^{pr2}$do_not_call_in_templates
属性设置为要从XML中获取文本,需要调用get_text()函数。在
不要使用:
使用:
^{pr2}$另外,建议使用lxml进行解析。安装lxml python并使用:
相关问题 更多 >
编程相关推荐