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

标签 python django beautifulsoup render

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

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

我做错了什么?

最佳答案

要从 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/

相关文章:

python - BeautifulSoup 找不到网页上存在的类?

python - 从 3.6 更新后无法为 python 3.7 安装 pip

python - 对多个网站使用一个 Scrapy 蜘蛛

使用 "pathlib.Path"寻址 BASE_DIR 时,django Pycharm 2020.2.2 无法解析静态文件

python - 如何在 Django 管理中测试覆盖函数?

python - 尝试保存模型实例时出现 Django AttributeError

python - 无法摆脱 BeautifulSoup 造成的导航问题

Python - 取每个第 n 个元素(就地)

python - 针对一个字符串测试多个子字符串

python - findall正则表达式字符串用什么漂亮的汤?