【问题标题】:How to retrieve and show the first result link using Google YouTube API?如何使用 Google YouTube API 检索和显示第一个结果链接?
【发布时间】:2020-10-30 16:56:18
【问题描述】:

我正在尝试使用 YouTube API V3 来提取您在 YouTube 上搜索内容时出现的第一个视频的 URL。

所以,I've been reading in the sample codebase 我需要“按关键字搜索”并将maxResults 参数的值更改为1
由于代码是 C#,我尝试使用在线转换器,但遇到了一个问题。我创建了一个新类,我插入了所有这些代码并通过 NuGet 安装了 Google API 和 YouTube API。

编辑:此代码已从 Console App 转换为 WinForm:

Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Google.Apis.Upload
Imports Google.Apis.Util.Store
Imports Google.Apis.YouTube.v3
Imports Google.Apis.YouTube.v3.Data

Namespace YouTube
    ''' <summary>
    ''' YouTube Data API v3 sample: search by keyword.
    ''' Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
    ''' See https://developers.google.com/api-client-library/dotnet/get_started
    '''
    ''' Set ApiKey to the API key value from the APIs & auth > Registered apps tab of
    '''   https://cloud.google.com/console
    ''' Please ensure that you have enabled the YouTube Data API for your project.
    ''' </summary>
   
         Public Async Function Run(ByVal videos As String) As Task(Of String)
            Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
                .ApiKey = "REPLACE_ME",
                .ApplicationName = [GetType]().ToString()
            })
            Dim searchListRequest = youtubeService.Search.List("snippet")
            searchListRequest.Q = "Google" ' Replace with your search term.
            searchListRequest.MaxResults = 1

            ' Call the search.list method to retrieve results matching the specified query term.
            Dim searchListResponse = Await searchListRequest.ExecuteAsync()

            Return searchListResponse.Items.FirstOrDefault()?.Id.VideoId

        End Function
    End Class
End Namespace

我应该如何从主窗体调用此命名空间,以便将我的搜索词 searchListRequest.Q = "Google" 替换为我使用文本框在主窗体中输入的内容?
我试图用以下方式调用它:

 Private Async Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
    MsgBox(Await Run())
End Sub

但 MessageBox 显示为空。
有没有办法称它已经改变了searchListRequest.Q
例如:msgbox(await Run(key word))

【问题讨论】:

    标签: vb.net winforms google-api youtube-api


    【解决方案1】:

    由于您要调用 Search 类 Run() 方法(此处重命名为 GetResultsAsync() 以匹配标准命名约定),您可以:

    • 创建一个新的类文件,将其添加到您的项目(或类库)中,
    • 将Async方法设为static(Shared),这样就可以直接调用了(不是必须的,不过看起来搜索结果这样处理比较好。当然可以创建@987654328的实例@class 代替)。
    • 使用文本框的内容将搜索词传递给方法。
      • 您可以在 TextBox.KeyDown 事件中处理 Enter 键
      • 如果需要,还可以添加一个执行相同操作的按钮
    • YouTube.GoogleSearch.GetResultAsync():
      • 设置.ApplicationName = Application.ProductName[GetType]().ToString() 是 C# 的错误翻译,即使更正也不会在这里做太多事情。或者直接使用为注册创建的名称。
      • searchListRequest.ExecuteAsync()的第一个结果返回为searchListResponse.Items.FirstOrDefault()?.Id.VideoId:如果没有返回结果,该方法将返回一个空字符串(Nothing
    • 添加和重载GetResultAsync(),接受用于在一段时间后取消任务的超时参数和允许取消 HTTP 请求任务的方法

    GoogleSearch 类重命名为您喜欢的任何名称 :)


    使用 Button 或 TextBox.KeyDown 事件调用GetResultAsync() 方法并将结果显示在另一个 TextBox 中:

    Private Async Sub txtSearch_KeyDown(sender As Object, e As KeyEventArgs) Handles txtSearch.KeyDown
        If (e.KeyCode = Keys.Enter) Then
            e.SuppressKeyPress = True
            txtSearch.Enabled = False
            SomeTextBox.Text = Await YouTube.GoogleSearch.GetResultAsync(txtSearch.Text)
            txtSearch.Enabled = True
        End If
    End Sub
    
    Private Async Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
        btnSearch.Enabled = False
        SomeTextBox.Text = Await YouTube.GoogleSearch.GetResultAsync(txtSearch.Text)
        btnSearch.Enabled = True
    End Sub
    
    Private Sub btnCancelSearch_Click(sender As Object, e As EventArgs) Handles btnCancelSearch.Click
        YouTube.GoogleSearch.Cancel()
    End Sub
    
    ' Call Cancel() when the Form closed 
    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        YouTube.GoogleSearch.Cancel()
    End Sub
    

    修改后的类对象。

    ► 注意:ExecuteAsync()方法要传入CancellationToken:如果用户同时关闭Form,则需要取消该Task,处理FormClosingFormClosed 事件。类似于此处显示的内容:

    How to let the code run smoothly using timers and different threads


    GoogleSearch 类可以是 internal (Friend)。

    编辑:

    • 添加了允许在取消请求之前指定超时(以毫秒为单位)的重载
    • 添加了一个静态 Cancel() 方法,用于取消当前请求并处置CancellationTokenSource
    Imports System.Threading.Tasks
    Imports Google.Apis.Auth.OAuth2
    Imports Google.Apis.Services
    Imports Google.Apis.YouTube.v3
    Imports Google.Apis.YouTube.v3.Data
    
    Namespace YouTube
        Public Class GoogleSearch
            Private Shared cts As CancellationTokenSource = Nothing
    
            Public Shared Async Function GetResultAsync(ByVal searchCriteria As String) As Task(Of String)
                Return Await GetResultAsync(searchCriteria, -1)
            End Function
    
            Public Shared Async Function GetResultAsync(ByVal searchCriteria As String, timeoutMilliseconds As Integer) As Task(Of String)
                If cts Is Nothing Then cts = New CancellationTokenSource(timeoutMilliseconds)
                Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
                    .ApiKey = "REPLACE_ME",
                    .ApplicationName = Application.ProductName
                })
    
                Dim searchListRequest = youtubeService.Search.List("snippet")
                searchListRequest.Q = searchCriteria
                searchListRequest.MaxResults = 1
    
                Try
                    Dim searchListResponse = Await searchListRequest.ExecuteAsync(cts.Token)
                    Return searchListResponse.Items.FirstOrDefault()?.Id.VideoId
                Catch exTCE As TaskCanceledException
                    ' Do whatever you see fit here
                    'MessageBox.Show(exTCE.Message)
                    Return Nothing
                Finally
                    Cancel(False)
                End Try
            End Function
    
            Public Shared Sub Cancel()
                Cancel(True)
            End Sub
    
            Private Shared Sub Cancel(cancelCTS As Boolean)
                If cancelCTS Then cts?.Cancel()
                cts?.Dispose()
                cts = Nothing
            End Sub
        End Class
    End Namespace
    

    【讨论】:

      猜你喜欢
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多