# 字幕

通过提供 **YouTube 视频 ID** 和一个 `language_code` 到 `youtube_subtitles` 来源来获取 YouTube 视频的文字记录。

{% hint style="warning" %}
字幕（隐藏式字幕）与转录文本是不同的。要提取标准转录文本，请使用 [YouTube Transcript](https://developers.oxylabs.io/documentation/cn/zhua-qu-jie-jue-fang-an/web-scraper-api/targets/youtube/youtube-transcript) 来源来获取 YouTube 视频的文字记录。
{% endhint %}

## 请求示例

下面的示例演示如何从上传者提供字幕的 YouTube 视频中检索英文隐藏式字幕。

{% tabs %}
{% tab title="cURL" %}

```shell
curl 'https://realtime.oxylabs.io/v1/queries' \
--user 'USERNAME:PASSWORD' \
-H 'Content-Type: application/json' \
-d '{
        "source": "youtube_subtitles",
        "query": "c4P_YuNnZ7U",
        "context": [
            {
                "key": "language_code",
                "value": "en"
            },
            {
                "key": "subtitle_origin",
                "value": "uploader_provided"
            }
        ]
    }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
from pprint import pprint

# 构建负载。
payload = {
    'source': 'youtube_subtitles',
    'query': 'c4P_YuNnZ7U',
    'context': [
        {
            'key': 'language_code',
            'value': 'en'
        },
        {
            'key': 'subtitle_origin',
            'value': 'uploader_provided'
        }
    ]
}

# 获取响应。
response = requests.request(
    'POST',
    'https://realtime.oxylabs.io/v1/queries',
    auth=('username', 'password'),
    json=payload,
)

# 打印包含结果的 JSON 响应。
pprint(response.json())
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const https = require("https");

const username = "USERNAME";
const password = "PASSWORD";
const body = {
    source: "youtube_subtitles",
    query: "c4P_YuNnZ7U",
    context: [
        {
            key: "language_code",
            value: "en",
        },
        {
            key: "subtitle_origin",
            value: "uploader_provided",
        },
    ],
};

const options = {
    hostname: "realtime.oxylabs.io",
    path: "/v1/queries",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        Authorization:
            "Basic " + Buffer.from(`${username}:${password}`).toString("base64"),
    },
};

const request = https.request(options, (response) => {
    let data = "";

    response.on("data", (chunk) => {
        data += chunk;
    });

    response.on("end", () => {
        const responseData = JSON.parse(data);
        console.log(JSON.stringify(responseData, null, 2));
    });
});

request.on("error", (error) => {
    console.error("Error:", error);
});

request.write(JSON.stringify(body));
request.end();
```

{% endtab %}

{% tab title="HTTP" %}

```http
# 您提交的整个字符串必须进行 URL 编码。

https://realtime.oxylabs.io/v1/queries?source=youtube_subtitles&query=c4P_YuNnZ7U&context=%5B%7B%22key%22%3A%22language_code%22%2C%22value%22%3A%22en%22%7D%2C%7B%22key%22%3A%22subtitle_origin%22%2C%22value%22%3A%22uploader_provided%22%7D%5D&access_token=12345abcde
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$params = array(
    'source' => 'youtube_subtitles',
    'query' => 'c4P_YuNnZ7U',
    'context' => array(
        array(
            'key' => 'language_code',
            'value' => 'en'
        ),
        array(
            'key' => 'subtitle_origin',
            'value' => 'uploader_provided'
        )
    )
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://realtime.oxylabs.io/v1/queries");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "USERNAME" . ":" . "PASSWORD");

$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
echo $result;

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}

curl_close($ch);
```

{% endtab %}

{% tab title="Golang" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	const Username = "USERNAME"
	const Password = "PASSWORD"

	// 使用带有 query 和 context 参数的负载定义。
	payload := map[string]interface{}{
		"source": "youtube_subtitles",
		"query":  "c4P_YuNnZ7U",
		"context": []map[string]string{
			{
				"key":   "language_code",
				"value": "en",
			},
			{
				"key":   "subtitle_origin",
				"value": "uploader_provided",
			},
		},
	}

	jsonValue, err := json.Marshal(payload)
	if err != nil {
		fmt.Println("Error marshalling JSON:", err)
		return
	}

	client := &http.Client{}
	request, err := http.NewRequest("POST", "https://realtime.oxylabs.io/v1/queries", bytes.NewBuffer(jsonValue))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	request.SetBasicAuth(Username, Password)
	request.Header.Set("Content-Type", "application/json")

	response, err := client.Do(request)
	if err != nil {
		fmt.Println("Error making request:", err)
		return
	}
	defer response.Body.Close()

	responseText, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}

	fmt.Println(string(responseText))
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;

namespace OxyApi
{
    class Program
    {
        static async Task Main()
        {
            const string Username = "USERNAME";
            const string Password = "PASSWORD";

            var parameters = new
            {
                source = "youtube_subtitles",
                query = "c4P_YuNnZ7U",
                context = new[]
                {
                    new { key = "language_code", value = "en" },
                    new { key = "subtitle_origin", value = "uploader_provided" }
                }
            };

            var client = new HttpClient();

            Uri baseUri = new Uri("https://realtime.oxylabs.io");
            client.BaseAddress = baseUri;

            var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/v1/queries");
            requestMessage.Content = JsonContent.Create(parameters);

            var authenticationString = $"{Username}:{Password}";
            var base64EncodedAuthenticationString = Convert.ToBase64String(Encoding.UTF8.GetBytes(authenticationString));
            requestMessage.Headers.Add("Authorization", "Basic " + base64EncodedAuthenticationString);

            try
            {
                var response = await client.SendAsync(requestMessage);
                response.EnsureSuccessStatusCode();

                var contents = await response.Content.ReadAsStringAsync();
                Console.WriteLine(contents);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
        }
    }
}
```

{% endtab %}

{% tab title="Java" %}

```java
package org.example;

import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.concurrent.TimeUnit;

public class Main implements Runnable {
    private static final String AUTHORIZATION_HEADER = "Authorization";
    public static final String USERNAME = "USERNAME";
    public static final String PASSWORD = "PASSWORD";

    public void run() {
        // 使用包含 context 参数的 JSON 负载构建请求
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("source", "youtube_subtitles");
        jsonObject.put("query", "c4P_YuNnZ7U");

        JSONArray contextArray = new JSONArray();
        contextArray.put(new JSONObject().put("key", "language_code").put("value", "en"));
        contextArray.put(new JSONObject().put("key", "subtitle_origin").put("value", "uploader_provided"));

        jsonObject.put("context", contextArray);

        Authenticator authenticator = (route, response) -> {
            String credential = Credentials.basic(USERNAME, PASSWORD);
            return response
                    .request()
                    .newBuilder()
                    .header(AUTHORIZATION_HEADER, credential)
                    .build();
        };

        var client = new OkHttpClient.Builder()
                .authenticator(authenticator)
                .readTimeout(180, TimeUnit.SECONDS)
                .build();

        var mediaType = MediaType.parse("application/json; charset=utf-8");
        var body = RequestBody.create(jsonObject.toString(), mediaType);
        var request = new Request.Builder()
                .url("https://realtime.oxylabs.io/v1/queries")
                .post(body)
                .build();

        try (var response = client.newCall(request).execute()) {
            if (response.body() != null) {
                try (var responseBody = response.body()) {
                    System.out.println(responseBody.string());
                }
            }
        } catch (Exception exception) {
            System.out.println("Error: " + exception.getMessage());
        }

        System.exit(0);
    }

    public static void main(String[] args) {
        new Thread(new Main()).start();
    }
}
```

{% endtab %}

{% tab title="JSON" %}

```json
{
    "source": "youtube_subtitles",
    "query": "c4P_YuNnZ7U",
    "context": [
        {
            "key": "language_code",
            "value": "en"
        },
        {
            "key": "subtitle_origin",
            "value": "uploader_provided"
        }
    ]
}
```

{% endtab %}
{% endtabs %}

我们的示例使用 [**Realtime**](https://developers.oxylabs.io/documentation/cn/zhua-qu-jie-jue-fang-an/web-scraper-api/integration-methods/realtime) 集成方法。如果您想使用 [**Proxy Endpoint**](https://developers.oxylabs.io/documentation/cn/zhua-qu-jie-jue-fang-an/web-scraper-api/integration-methods/proxy-endpoint)**,** 或异步的 [**Push-Pull**](https://developers.oxylabs.io/documentation/cn/zhua-qu-jie-jue-fang-an/web-scraper-api/integration-methods/push-pull) 集成，请参阅 [**Integration Methods** ](https://developers.oxylabs.io/documentation/cn/zhua-qu-jie-jue-fang-an/web-scraper-api/integration-methods)章节。

{% file src="<https://2655358775-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FzrXw45naRpCZ0Ku9AjY1%2Fuploads%2F82Mwlry3L0OA9935eZK0%2FYT_subtitles_output.json?alt=media&token=f1c773cc-47fa-41ce-b7da-17d47e181ad2>" %}

## 请求参数值

### 通用

<table><thead><tr><th width="227">参数</th><th width="289.3333333333333">说明</th><th>默认值</th></tr></thead><tbody><tr><td><mark style="background-color:green;"><strong><code>source</code></strong></mark></td><td>设置要使用的爬虫。</td><td><code>youtube_subtitles</code></td></tr><tr><td><mark style="background-color:green;"><strong><code>query</code></strong></mark></td><td>YouTube 视频 ID。</td><td>–</td></tr><tr><td><strong>context:</strong><br><mark style="background-color:green;"><strong><code>language_code</code></strong></mark></td><td>指定字幕的语言。可用值请参见 <a href="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FzrXw45naRpCZ0Ku9AjY1%2Fuploads%2FpKzuNdn6pgiePWHADWVQ%2Flanguages.json?alt=media&#x26;token=bb8d9eac-8268-4f28-bd2b-6a084c4862ea"><strong>这里</strong></a>.<br><strong>注意</strong>: 如果提供的 <code>language_code</code> 在 YouTube 视频中没有匹配的字幕/隐藏式字幕时，结果返回一个 <code>404</code> 状态。</td><td>–</td></tr><tr><td><code>context:</code><br><code>subtitle_origin</code></td><td>指定是否检索由……提供的字幕， <code>auto_generated</code> 或 <code>uploader_provided</code>.</td><td>–</td></tr><tr><td><code>callback_url</code></td><td>您回调端点的 URL。 <a href="../../../integration-methods/push-pull#callback"><strong>更多信息</strong></a>.</td><td>–</td></tr></tbody></table>

&#x20;    – 必填参数


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developers.oxylabs.io/documentation/cn/zhua-qu-jie-jue-fang-an/web-scraper-api/targets/youtube/youtube-subtitles.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
