python - 从外部网站获取元描述

标签 python django

我需要提取外部网站的元描述。我已经搜索过了,也许简单的答案已经在那里,但我无法将其应用到我的代码中。

目前我可以通过以下方式获得它的标题:

external_sites_html = urllib.request.urlopen(url)
soup = BeautifulSoup(external_sites_html)
title = soup.title.string

但是,描述有点棘手。它可以采用以下形式:

<meta name="og:description" content="blabla"
<meta property="og:description" content="blabla"
<meta name="description" content="blabla"

所以我想要的是提取出现在 html 中的第一个。然后它将被添加到数据库中:

entry.description = extracted_desc
entry.save

如果它根本没有找到任何描述,那么它只会继续保存标题。

最佳答案

您可以在 soup 对象上使用 find 方法并查找具有特定属性的标签。在这里,我们需要找到 meta 标签,其 name 属性等于 og:descriptiondescriptionproperty 属性等于 description

# First get the meta description tag
description = soup.find('meta', attrs={'name':'og:description'}) or soup.find('meta', attrs={'property':'description'}) or soup.find('meta', attrs={'name':'description'})

# If description meta tag was found, then get the content attribute and save it to db entry
if description:
    entry.description = description.get('content')

关于python - 从外部网站获取元描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22318095/

相关文章:

python - Elasticsearch-py 使用脚本更新 API

javascript - VS代码: "Go to definition" from JS url (view url) to the Django view

python - 在 OSQA (django python) 上添加问题时,其正文为空

python - 序列化器中的外键不可 json 序列化

python - pandas/numpy 的轴与 R 的 MARGIN 相反吗?

python - 显示 2 个不同大小的 DataFrame 的共同元素和差异

python - 反混淆:简化 Python3 表达式

Python Django Rest 框架身份验证

python - 当查询返回Null(无对象)时如何在django模板中显示 "nothing found"?

python - 加入字符串。生成器或列表理解?