Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
youtube api v3页面标记_Youtube_Youtube Api - Fatal编程技术网

youtube api v3页面标记

youtube api v3页面标记,youtube,youtube-api,Youtube,Youtube Api,我正在使用搜索api和nextpagetoken对结果进行分页。 但我不能用这种方式检索所有结果。在大约455000个结果中,我只能得到500个结果 以下是获取搜索结果的java代码: youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {public void initialize(HttpRequest request) throws IOExce

我正在使用搜索api和nextpagetoken对结果进行分页。 但我不能用这种方式检索所有结果。在大约455000个结果中,我只能得到500个结果

以下是获取搜索结果的java代码:

youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {public void initialize(HttpRequest request) throws IOException {}           }).setApplicationName("youtube-search").build();

YouTube.Search.List search = youtube.search().list("id,snippet");
String apiKey = properties.getProperty("youtube.apikey");
search.setKey(apiKey);
search.setType("video");
search.setMaxResults(50);
search.setQ(queryTerm);
boolean allResultsRead = false;
while (! allResultsRead){
SearchListResponse searchResponse = search.execute();
System.out.println("Printed " +  searchResponse.getPageInfo().getResultsPerPage() + " out of " + searchResponse.getPageInfo().getTotalResults() + ". Current page token: " + search.getPageToken() + "Next page token: " + searchResponse.getNextPageToken() + ". Prev page token" + searchResponse.getPrevPageToken());
if (searchResponse.getNextPageToken() == null)
{
    allResultsRead = true;                          
    search = youtube.search().list("id,snippet");
    search.setKey(apiKey);
    search.setType("video");
    search.setMaxResults(50);
}
else
{
   search.setPageToken(searchResponse.getNextPageToken());
}}
输出是

Printed 50 out of 455085. Current page token: null Next page token: CDIQAA. Prev page token null
Printed 50 out of 454983. Current page token: CDIQAA Next page token: CGQQAA. Prev page token CDIQAQ
Printed 50 out of 455081. Current page token: CGQQAA Next page token: CJYBEAA. Prev page token CGQQAQ
Printed 50 out of 454981. Current page token: CJYBEAA Next page token: CMgBEAA. Prev page token CJYBEAE
Printed 50 out of 455081. Current page token: CMgBEAA Next page token: CPoBEAA. Prev page token CMgBEAE
Printed 50 out of 454981. Current page token: CPoBEAA Next page token: CKwCEAA. Prev page token CPoBEAE
Printed 50 out of 455081. Current page token: CKwCEAA Next page token: CN4CEAA. Prev page token CKwCEAE
Printed 50 out of 454980. Current page token: CN4CEAA Next page token: CJADEAA. Prev page token CN4CEAE
Printed 50 out of 455081. Current page token: CJADEAA Next page token: CMIDEAA. Prev page token CJADEAE
Printed 50 out of 455081. Current page token: CMIDEAA Next page token: null. Prev page token CMIDEAE
经过10次while循环迭代后,它退出,因为下一页标记为null

我是Yotube API的新手,不确定我在这里做错了什么。我有两个问题: 1.我如何得到所有的结果? 2.为什么第3页的上一页标记与第2页的当前标记不同


任何帮助都将不胜感激。谢谢

你正在体验你想要的;使用nextPageToken,最多只能获得500个结果。如果您对如何实现这一点感兴趣,可以通读以下内容:

但作为这条线索的总结,基本上可以归结为这样一个事实:YouTube上有如此多的数据,搜索算法与大多数人认为的完全不同。这不仅仅是对字段中的内容进行简单的数据库搜索,还有数量惊人的信号正在被处理以使结果相关,在大约500个结果之后,算法开始失去使结果有价值的能力

有一件事帮助我了解了这一点,那就是当YouTube谈论搜索时,他们谈论的是概率而不是匹配,因此结果是根据你的参数排序的,根据它们与你的查询相关的可能性排序的。当你翻页的时候,你最终到达了一个点,从统计上来说,相关性的概率很低,以至于在计算上不值得让那些结果回来。所以500是决定的极限

(还要注意的是,“结果”的数量并不是匹配的近似值,而是潜在匹配的近似值,但当你开始检索它们时,许多可能的匹配项会被丢弃,因为它们根本不相关……所以这个数字并不是人们所想的那样。谷歌搜索也是如此。)

你可能想知道为什么YouTube搜索功能是这样的,而不是进行更传统的字符串/数据匹配;有这么多的搜索量,如果他们真的要对每个查询的所有数据进行完整的搜索,那么你一次只能等待几分钟,如果不是更多的话。这真是一个技术奇迹,如果你想一想,当算法在预测、概率等方面发挥作用时,它们是如何在前500个案例中获得如此相关的结果的


至于您的第二个问题,页面标记并不表示一组唯一的结果,而是表示一种算法状态,因此是指向您的查询、查询进度和查询方向的指针。。。例如,迭代3被迭代2的nextPageToken和迭代4的prevPageToken引用,但这两个标记稍有不同,因此它们可以指示它们来自的方向。

您可以传递页面nextPageToken并将其作为pagetoken的参数

这将显示nex页面,我编写了一个vardamp来向您显示页面标记不是相同的,只需复制此代码并运行它,并确保您已将api资源文件夹放在插件的同一文件夹中

    <?php
    function doit(){if (isset($_GET['q']) && $_GET['maxResults'] ) {
      // Call set_include_path() as needed to point to your client library.
     // require_once ($_SERVER["DOCUMENT_ROOT"].'/API/youtube/google-api-php-client/src/Google_Client.php');
     // require_once ($_SERVER["DOCUMENT_ROOT"].'/API/youtube/google-api-php-client/src/contrib/Google_YouTubeService.php');
      set_include_path("./google-api-php-client/src");
      require_once 'Google_Client.php';
      require_once 'contrib/Google_YouTubeService.php';
      /* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
      Google APIs Console <http://code.google.com/apis/console#access>
      Please ensure that you have enabled the YouTube Data API for your project. */
      $DEVELOPER_KEY = 'AIzaSyCgHHDrx5ufQlkXcSc8nm5uqrsNdXizbMs';

                        //  the old one    AIzaSyDOkg-u9jnhP-WnzX5WPJyV1sc5QQrtuyc 



    $client = new Google_Client();
      $client->setDeveloperKey($DEVELOPER_KEY);

      $youtube = new Google_YoutubeService($client);

      try {
        $searchResponse = $youtube->search->listSearch('id,snippet', array(
          'q' => $_GET['q'],
          'maxResults' => $_GET['maxResults'],

    ));
    var_dump($searchResponse);


    $searchResponse2 = $youtube->search->listSearch('id,snippet', array(
      'q' => $_GET['q'],
      'maxResults' => $_GET['maxResults'],
      'pageToken' => $searchResponse['nextPageToken'],
    ));
    var_dump($searchResponse2);
    exit;


    $videos = '';
    $channels = '';
      foreach ($searchResponse['items'] as $searchResult) {
          switch ($searchResult['id']['kind']) {
         case 'youtube#video':

          $videoId =$searchResult['id']['videoId'];
          $title = $searchResult['snippet']['title'];
          $publishedAt= $searchResult['snippet']['publishedAt'];
          $description = $searchResult['snippet']['description'];
          $iamge_url =  $searchResult['snippet'] ['thumbnails']['default']['url'];
          $image_high  = $searchResult['snippet'] ['thumbnails']['high']['url'];




          echo  '<div class="souligne" id="'.$videoId.'">

            <div >
            <a href=http://www.youtube.com/watch?v='.$videoId.' target=_blank"  >
            <img src="'.$iamge_url .'"   width ="150px" /> 
            </a> 
            </div>
            <div class="title">'.$title.'</div>
            <div class="des"> '.$description.' </div>
            <a id="'.$videoId.'" onclick="supp(this)" class="linkeda"> 
                + ADD
            </a>                
            </div>'
            ;
          break;
      }
    }
    echo  ' </ul></form>';

       } catch (Google_ServiceException $e) {
        $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
      } catch (Google_Exception $e) {
        $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
      }
    }}
       doit();
    ?>
    <!doctype html>
    <html>
      <head>
        <title>YouTube Search</title>
    <link href="//www.w3resource.com/includes/bootstrap.css" rel="stylesheet">
    <style type="text/css">
    body{margin-top: 50px; margin-left: 50px}
    </style>
      </head>
      <body>
        <form method="GET">
      <div>
        Search Term: <input type="search" id="q" name="q" placeholder="Enter Search Term">
      </div>
      <div>

        Max Results: <input type="number" id="maxResults" name="maxResults" min="1" max="1000000" step="1" value="25">
      </div>
      <div>
        page: <input type="number" id="startIndex" name="startIndex" min="1" max="50" step="1" value="2">
      </div>
      <input type="submit" value="Search">
    </form>

<h3>Videos</h3>
    <ul><?php if(isset($videos))echo $videos; ?></ul>
    <h3>Channels</h3>
    <ul><?php if(isset($channels)) echo $channels; ?></ul>
</body>
</html>

我明白了,你没有在设置域中包含“nextPageToken”

例如:

public class ABC {
private YouTube youtube;
private YouTube.Search.List query;

public static final String KEY = "YOUR API KEY";

public YoutubeConnector(Context context) {
    youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest httpRequest) throws IOException {
        }
    }).setApplicationName(context.getString(R.string.app_name)).build();

    try {
        query = youtube.search().list("id,snippet");
        query.setMaxResults(Long.parseLong("10"));
        query.setKey(KEY);
        query.setType("video");
        query.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url),nextPageToken");
    } catch (IOException e) {
        Log.d("YC", "Could not initialize: " + e.getMessage());
    }
}

public List<VideoItem> search(String keywords) {
    query.setQ(keywords);
        try {
            List<VideoItem> items = new ArrayList<VideoItem>();
            String nextToken = "";
            int i = 0;
            do {
                query.setPageToken(nextToken);
                SearchListResponse response = query.execute();
                List<SearchResult> results = response.getItems();
                for (SearchResult result : results) {
                    VideoItem item = new VideoItem();
                    item.setTitle(result.getSnippet().getTitle());
                        item.setDescription(result.getSnippet().getDescription());
                    item.setThumbnailURL(result.getSnippet().getThumbnails().getDefault().getUrl());
                    item.setId(result.getId().getVideoId());
                    items.add(item);
                }
                nextToken = response.getNextPageToken();
                i ++;
                System.out.println("nextToken :  "+ nextToken);
            } while (nextToken != null && i < 20);

            return items;
        } catch (IOException e) {
            Log.d("YC", "Could not search: " + e);
            return null;
        }

}
}
公共类ABC{
私人YouTube;
私有YouTube.Search.List查询;
public static final String KEY=“您的API密钥”;
公共YoutubeConnector(上下文){
youtube=new youtube.Builder(new NetHttpTransport()、new JacksonFactory()、new HttpRequestInitializer()){
@凌驾
公共无效初始化(HttpRequest HttpRequest)引发IOException{
}
}).setApplicationName(context.getString(R.string.app_name)).build();
试一试{
query=youtube.search().list(“id,snippet”);
setMaxResults(Long.parseLong(“10”));
query.setKey(KEY);
query.setType(“视频”);
设置字段(“项目(id/videoId、代码片段/标题、代码片段/描述、代码片段/缩略图/默认值/url)、nextPageToken”);
}捕获(IOE异常){
Log.d(“YC”,“无法初始化:”+e.getMessage());
}
}
公共列表搜索(字符串关键字){
setQ(关键字);
试一试{
列表项=新建ArrayList();
字符串nextToken=“”;
int i=0;
做{
query.setPageToken(nextToken);
SearchListResponse=query.execute();
列表结果=response.getItems();
for(搜索结果:结果){
VideoItem=新的VideoItem();
item.setTitle(result.getSnippet().getTitle());
item.setDescription(result.getSnippet().getDescription());
item.setThumbnailURL(result.getSnippet().getThumbnails().getDefault().getUrl());
item.setId(result.getId().getVideoId());
项目。添加(项目);
}
nextToken=response.getNextPageToken();
i++;
System.out.println(“nextToken:+nextToken”);
}while(nextToken!=null&&i<20);
退货项目;
}捕获(IOE异常){
Log.d(“YC”,“无法搜索:+e”);
返回null;
}
}
}
我希望这对你有帮助