search
HomeBackend DevelopmentPHP TutorialMetadata scraping using the New York Times API

Metadata scraping using the New York Times API

简介

上周,我写了一篇关于抓取网页以收集元数据的介绍,并提到不可能抓取《纽约时报》网站。 《纽约时报》付费墙会阻止您收集基本元数据的尝试。但有一种方法可以使用纽约时报 API 来解决这个问题。

最近我开始在 Yii 平台上构建一个社区网站,我将在以后的教程中发布该网站。我希望能够轻松添加与网站内容相关的链接。虽然人们可以轻松地将 URL 粘贴到表单中,但提供标题和来源信息却非常耗时。

因此,在今天的教程中,我将扩展我最近编写的抓取代码,以在添加《纽约时报》链接时利用《纽约时报》API 来收集头条新闻。

请记住,我参与了下面的评论主题,所以请告诉我您的想法!您还可以通过 Twitter @lookahead_io 与我联系。

开始使用

注册 API 密钥

Metadata scraping using the New York Times API

首先,让我们注册并请求 API 密钥:

Metadata scraping using the New York Times API

提交表单后,您将通过电子邮件收到密钥:

Metadata scraping using the New York Times API

探索纽约时报 API

Metadata scraping using the New York Times API

The Times 提供以下类别的 API:

  • 存档
  • 文章搜索
  • 书籍
  • 社区
  • 地理
  • 最受欢迎
  • 电影评论
  • 语义
  • 泰晤士报
  • 时代标签
  • 头条新闻

很多。并且,在“图库”页面中,您可以单击任何主题来查看各个 API 类别文档:

Metadata scraping using the New York Times API

《纽约时报》使用 LucyBot 为其 API 文档提供支持,并且有一个有用的常见问题解答:

Metadata scraping using the New York Times API

他们甚至向您展示如何快速获取 API 使用限制(您需要插入密钥):

 curl --head 
   https://api.nytimes.com/svc/books/v3/lists/overview.json?api-key=<your-api-key>
    2>/dev/null | grep -i "X-RateLimit"
    X-RateLimit-Limit-day: 1000
    X-RateLimit-Limit-second: 5
    X-RateLimit-Remaining-day: 180
    X-RateLimit-Remaining-second: 5

我最初很难理解该文档 - 它是基于参数的规范,而不是编程指南。不过,我在纽约时报 API GitHub 页面上发布了一些问题,这些问题很快就得到了有用的解答。

使用文章搜索

在今天的节目中,我将重点介绍如何使用《纽约时报》文章搜索。基本上,我们将扩展上一个教程中的创建链接表单:

Metadata scraping using the New York Times API

当用户点击查找时,我们将向 链接::grab($url)。这是 jQuery:

$(document).on("click", '[id=lookup]', function(event) {
  $.ajax({
     url: $('#url_prefix').val()+'/link/grab',
     data: {url:   $('#url').val()},
     success: function(data) {
       $('#title').val(data);
       return true;
     }
  });
});

这是控制器和模型方法:

// Controller call via AJAX Lookup request
public static function actionGrab($url) {
  Yii::$app->response->format = Response::FORMAT_JSON;
  return Link::grab($url);
}
...
// Link::grab() method
public static function grab($url) {
  //clean up url for hostname
  $source_url = parse_url($url);
  $source_url = $source_url['host'];  
  $source_url=str_ireplace('www.','',$source_url);
  $source_url = trim($source_url,' \\');
  // use the NYT API when hostname == nytimes.com 
  if ($source_url=='nytimes.com') {
   ...

接下来,让我们使用 API 密钥发出文章搜索请求:

    $nytKey=Yii::$app->params['nytapi'];    
    $curl_dest = 'http://api.nytimes.com
        /svc/search/v2/articlesearch.json?fl=headline&fq=web_url:%22'.
        $url.'%22&api-key='.$nytKey;
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_URL,$curl_dest);
    $result = json_decode(curl_exec($curl));
    $title = $result->response->docs[0]->headline->main;
  } else {
    // not NYT, use the standard metatag scraper from last episode
         ...
    }
  }
  return $title;
}

它的工作原理非常简单 - 这是生成的标题(顺便说一句,气候变化正在杀死北极熊,我们应该关心):

Metadata scraping using the New York Times API

如果您想了解 API 请求的更多详细信息,只需向 ?fl 添加其他参数即可=headline 请求例如 关键字 lead_paragraph:

Yii::$app->response->format = Response::FORMAT_JSON;
$nytKey=Yii::$app->params['nytapi'];
$curl_dest = 'http://api.nytimes.com/svc/search/v2/articlesearch.json?'.
  'fl=headline,keywords,lead_paragraph&fq=web_url:%22'.$url.'%22&api-key='.$nytKey;
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL,$curl_dest);
$result = json_decode(curl_exec($curl));
var_dump($result);

结果如下:

Metadata scraping using the New York Times API

也许我会在接下来的剧集中编写一个 PHP 库来更好地解析 NYT API,但此代码打破了关键字和引导段落:

Yii::$app->response->format = Response::FORMAT_JSON;
$nytKey=Yii::$app->params['nytapi'];
$curl_dest = 'http://api.nytimes.com/svc/search/v2/articlesearch.json?'.
  'fl=headline,keywords,lead_paragraph&fq=web_url:%22'.$url.'%22&api-key='.$nytKey;
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL,$curl_dest);
$result = json_decode(curl_exec($curl));
echo $result->response->docs[0]->headline->main.'<br />'.'<br />';
echo $result->response->docs[0]->lead_paragraph.'<br />'.'<br />';
foreach ($result->response->docs[0]->keywords as $k) {
  echo $k->value.'<br/>';
}

以下是本文显示的内容:

Polar Bears’ Path to Decline Runs Through Alaskan Village

The bears that come here are climate refugees, on land because
the sea ice they rely on for hunting seals is receding.

Polar Bears
Greenhouse Gas Emissions
Alaska
Global Warming
Endangered and Extinct Species
International Union for Conservation of Nature
National Snow and Ice Data Center
Polar Bears International
United States Geological Survey

希望这能开始扩展您对如何使用这些 API 的想象力。现在可能实现的事情非常令人兴奋。

结束中

纽约时报 API 非常有用,我很高兴看到他们向开发者社区提供它。通过 GitHub 获得如此快速的 API 支持也令人耳目一新——我只是没想到会这样。请记住,它适用于非商业项目。如果您有一些赚钱的想法,请给他们留言,看看他们是否愿意与您合作。出版商渴望新的收入来源。

I hope you find these web scraping snippets helpful and implement them into your projects. If you want to watch today's show, you can try some web scraping on my website Active Together .

Please share any thoughts and feedback in the comments. You can also always contact me directly on Twitter @lookahead_io. Be sure to check out my instructor page and other series: Building Your Startup with PHP and Programming with Yii2.

  • New York Times API Library
  • The New York Times Public API Specification on GitHub
  • How to crawl metadata in web pages (Envato Tuts)
  • How to use Node.js and jQuery to crawl web pages (Envato Tuts)
  • Build your first Web Scraper in Ruby (Envato Tuts)

The above is the detailed content of Metadata scraping using the New York Times API. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment