我想知道如何使用它的 URL提取外部站点的Title和Metadescription。我找到了一些解决方案,但不适用于 django/python。
目前我的代码添加了一个指向数据库的链接,我想让它在添加后转到该链接,然后使用相应的Title和更新条目Metadescription。
能够检索og诸如meta property="og:url.
谢谢你。
要访问外部站点的标题或描述,您必须做两件事。
1) 您需要获取 html 外部站点。2)您需要解析html并获取标题元素和元元素。
第一部分很简单:
import urllib2
opener = urllib2.build_opener()
external_sites_html = opener.open(external_sites_url).read()
Run Code Online (Sandbox Code Playgroud)
第二部分更难,因为我们需要使用外部库来解析 html,我喜欢一个名为 BeautifulSoup 的库,因为它有一个非常好的 api。(程序员很容易使用。)
from bs4 import BeautifulSoup
soup = BeautifulSoup(external_sites_html)
# Now we can get the tags of the external site from the soup variable.
title = soup.title.string
Run Code Online (Sandbox Code Playgroud)
但是,重要的是要记住,外部站点在我们获取它时可能只会响应缓慢,因此将外部站点记录在您的数据库中,然后向用户返回回复可能是明智的。然后在其他一些过程中,您应该去获取 url 并将额外信息添加到数据库中。如果在回复中返回额外信息很重要,那么您不能在后台执行此操作,而必须让您的用户等待。