Получить название и описание Google и Yahoo? - PullRequest
0 голосов
/ 24 июня 2019

Я хочу создать API, который возвращает заголовок и описание данного URL.

Я пробую решение, представленное здесь: https://stackoverflow.com/a/3711554/5618358 с текущим улучшением:

  • Добавить поддержку протокола Open Graph
  • Переместить его в каркас Laravel.

К сожалению, он не работает, когда вы передаете Yahoo и Google URL.Но работайте с другими URL-адресами, например с очарованием. Github.com

Я пытаюсь шаг за шагом вывести параметры кода и понимаю, что Yahoo возвращает уродливый код, который не может быть обработан, а в HTML-коде Google нет описания.метатег.

Насколько похожи другие сайты:

работает?

Пожалуйста, помогите мне решить эту проблему.Я прошу прощения за мой плохой английский.

//In routes/api.php
Route::get('/links/helper/meta-tag-extractor', function(Request $request){
    $url = $request->get('url');
    $result = [];
    function file_get_contents_curl($url)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

    $html = file_get_contents_curl($url);

    //parsing begins here:
    $doc = new DOMDocument();
    @$doc->loadHTML($html);
    $nodes = $doc->getElementsByTagName('title');

    //get and display what you need:
    //This part issue error for url Yahoo.com:
    $result['title'] = $nodes->item(0)->nodeValue;

    $metas = $doc->getElementsByTagName('meta');

    for ($i = 0; $i < $metas->length; $i++)
    {
        $meta = $metas->item($i);
        if($meta->getAttribute('name') == 'description') {
            $result['description'] = $meta->getAttribute('content');
        }

        //property="og:description"
        //<meta property="og:description"
        //  content="Sean Connery found fame and fortune as the
        //           suave, sophisticated British agent, James Bond." />
        if($meta->getAttribute('property') == 'og:description') {
            $result['og:description'] = $meta->getAttribute('property');
        }
    }
//    We haven't 'description' or 'og:description' in result for url: Google.com
//    But for url Github.com works like a charm with result:
//    {
//        "title": "The world’s leading software development platform · GitHub",
//        "description": "GitHub brings together the world’s largest community of developers to discover, share, and build better software. From open source projects to private team repositories, we’re your all-in-one platform for collaborative development.",
//        "og:description": "og:description"
//    }
    return $result;
});

1 Ответ

0 голосов
/ 24 июня 2019

После долгих усилий я решил часть проблемы.

Я решил проблему с Yahoo, так что я могу получить ее информацию.

Но для Google URL не работает.

Google не имеет описания или og: описание в своем источнике, когда я получаю его по серверу.

Результат кода для Yahoo:

{
   "title": "Yahoo",
   "description": "News, email and search are just the beginning. Discover more every day. Find your yodel.",
   "og:title": "Yahoo",
   "og:type": "website",
   "og:url": "http://www.yahoo.com",
   "og:description": "News, email and search are just the beginning. Discover more 
   every day. Find your yodel.",
   "og:image": "https://s.yimg.com/dh/ap/default/130909/y_200_a.png",
   "og:site_name": "Yahoo"
}

Но результат кода дляGoogle является:

{
  "title": "Google"
}

Пожалуйста, помогите мне о Google ....

Новый исходный код:

//In routes/api.php
Route::get('/links/helper/meta-tag-extractor', function(Request $request){
    $url = $request->get('url');
    $result = [];
    function file_get_contents_curl($url)
    {
        $ch = curl_init();
        $timeout = 10;

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3000);
        curl_setopt($ch,CURLOPT_ENCODING , "gzip");
        curl_setopt($ch, CURLOPT_HEADER, 0);

        $data = curl_exec($ch);

        curl_close($ch);

        return $data;
    }

    $html = file_get_contents_curl($url);

    $doc = new DOMDocument();
    @$doc->loadHTML($html);
//    echo $html;

    $nodes = $doc->getElementsByTagName('title');

    if ($nodes->count()) {
        $result['title'] = $nodes->item(0)->nodeValue;
    }


    $metas = $doc->getElementsByTagName('meta');

    for ($i = 0; $i < $metas->length; $i++)
    {
        $meta = $metas->item($i);
        if($meta->getAttribute('name') == 'description') {
            $result['description'] = $meta->getAttribute('content');
        }

        if(substr( $meta->getAttribute('property'), 0, 3 ) === 'og:') {
            $result[$meta->getAttribute('property')] = $meta->getAttribute('content');
        }
    }
    return $result;
});
...