Kaushik S Kaushik S - 2 months ago 6
Python Question

Not getting any output in Django for BeautifulSoup

I am trying BeautifulSoup4 in Django and I parsed an XML page with it. When I try the parsing the same XML page in a python interpreter in a different way, it works fine. But in Django, I get a page as shown below.

enter image description here

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 %}


What is that I am doing wrong?

Answer

To get text from XML, you need to call get_text() function.

Don't use:

items.title

Use:

items.title.get_text()

Also, it's recommended to use lxml for parsing. Install lxml python and use:

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