我正在 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 %}
我做错了什么?
最佳答案
要从 XML 中获取文本,您需要调用 get_text() 函数。
不要使用:
items.title
使用:
items.title.get_text()
另外,推荐使用lxml进行解析。安装 lxml python 并使用:
soup = BeautifulSoup(urlopen(xmllink), 'lxml-xml')
关于python - BeautifulSoup 在 Django 中没有得到任何输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39564141/