抓取标题、描述和关键字的可靠方法
A reliable way to scrape title, description and keywords
目前我正在使用 CURL 抓取网站。 我想可靠地获取标题、描述和关键字。
//Parse for the title, description and keywords
if (strlen($link_html) > 0)
{
$tags = get_meta_tags($link); // name
$link_keywords = $tags['keywords']; // php documentation
$link_description = $tags['description'];
}
唯一的问题是人们现在使用各种元标记,例如 open graph <meta property="og:title" content="The Rock" />
。他们还改变了很多标签 <title> <Title> <TITLE> <tiTle>
。很难可靠地获得这些。
我真的需要一些代码来一致地提取这些变量。如果有一些标题、关键字和描述,它会找到它。因为现在看来很碰运气。
也许有一种方法可以将所有标题提取到标题数组中? 然后抓取网络开发人员可以选择最好的一个记录在他们的数据库中。这同样适用于关键字和描述。
This is not a duplicate. I have searched through Whosebug and
nowhere is this solution to place all "title", "keywords" and
"description" type tags into arrays.
通常 get_meta_tags()
应该可以满足您的大部分需求,您只需设置一组级联检查,从每个元数据系统中抽取所需字段,直到找到一个。例如,像这样:
function get_title($url) {
$tags = get_meta_tags($url);
$props = get_meta_props($url);
return @tags["title"] || @props["og:title"] || ...
}
上面的实现显然效率不高(因为如果我们像这样实现所有 getter,你会为每个 getter 重新加载 URL),而我没有t 实施 get_meta_props()
- 使用 pcre_*
正确实施是有问题的,使用 DOMDocument
.
实施是乏味的
尽管需要大量工作,但正确的实现仍然是微不足道的——这是外部库解决问题的经典场景!幸运的是,有一个可以做到这一点——简单地称为 "Embed",你可以在 github 上找到它,或者使用 composer 只是 运行
composer require embed/embed
目前我正在使用 CURL 抓取网站。 我想可靠地获取标题、描述和关键字。
//Parse for the title, description and keywords
if (strlen($link_html) > 0)
{
$tags = get_meta_tags($link); // name
$link_keywords = $tags['keywords']; // php documentation
$link_description = $tags['description'];
}
唯一的问题是人们现在使用各种元标记,例如 open graph <meta property="og:title" content="The Rock" />
。他们还改变了很多标签 <title> <Title> <TITLE> <tiTle>
。很难可靠地获得这些。
我真的需要一些代码来一致地提取这些变量。如果有一些标题、关键字和描述,它会找到它。因为现在看来很碰运气。
也许有一种方法可以将所有标题提取到标题数组中? 然后抓取网络开发人员可以选择最好的一个记录在他们的数据库中。这同样适用于关键字和描述。
This is not a duplicate. I have searched through Whosebug and nowhere is this solution to place all "title", "keywords" and "description" type tags into arrays.
通常 get_meta_tags()
应该可以满足您的大部分需求,您只需设置一组级联检查,从每个元数据系统中抽取所需字段,直到找到一个。例如,像这样:
function get_title($url) {
$tags = get_meta_tags($url);
$props = get_meta_props($url);
return @tags["title"] || @props["og:title"] || ...
}
上面的实现显然效率不高(因为如果我们像这样实现所有 getter,你会为每个 getter 重新加载 URL),而我没有t 实施 get_meta_props()
- 使用 pcre_*
正确实施是有问题的,使用 DOMDocument
.
尽管需要大量工作,但正确的实现仍然是微不足道的——这是外部库解决问题的经典场景!幸运的是,有一个可以做到这一点——简单地称为 "Embed",你可以在 github 上找到它,或者使用 composer 只是 运行
composer require embed/embed