> For the complete documentation index, see [llms.txt](https://developers.oxylabs.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.oxylabs.io/api-targets/cn/llms-and-ai/gemini.md).

# Gemini

通过提交提示词提取 Gemini 响应，并以结构化 JSON、纯文本或 Markdown 接收解析后的数据。

该 `gemini` source 允许您向 Google Gemini 提交提示词，并接收经过解析的结构化响应，包括纯文本和 Markdown 答案。

## 请求示例

以下代码示例展示了如何使用以下方式向 Gemini 提交提示词 [**Push-Pull**](/products/cn/web-scraper-api/integration-methods/push-pull.md).

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

```bash
curl 'https://data.oxylabs.io/v1/queries' \\
--user 'USERNAME:PASSWORD' \\
-H 'Content-Type: application/json' \\
-d '{
        "source": "gemini",
        "prompt": "best supplements for better sleep",
        "parse": true,
        "geo_location": "United States",
        "callback_url": "https://your-server.com/oxylabs-callback"
    }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
from pprint import pprint

# 结构化载荷。
payload = {
    'source': 'gemini',
    'prompt': 'best supplements for better sleep',
    'parse': True,
    'geo_location': "United States",
    'callback_url': "https://your-server.com/oxylabs-callback"
}

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

# Print prettified response to stdout.
pprint(response.json())
```

{% endtab %}

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

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

const username = "USERNAME";
const password = "PASSWORD";
const body = {
    source: "gemini",
    prompt: "best supplements for better sleep",
    解析：true,
    geo_location: "United States",
    callback_url: "https://your-server.com/oxylabs-callback"
};

const options = {
    hostname: "data.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="PHP" %}

```php
<?php

$params = array(
    'source' => 'gemini',
    'prompt' => 'best supplements for better sleep',
    'parse' => true,
    'geo_location' => "United States",
    'callback_url' => "https://your-server.com/oxylabs-callback"
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://data.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="Go" %}

```go
package main

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

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

payload := map[string]interface{}{
"source":       "gemini",
"prompt":       "改善睡眠的最佳补充剂",
"parse":        true,
"geo_location": "United States",
"callback_url": "https://your-server.com/oxylabs-callback",
}

jsonValue, _ := json.Marshal(payload)

client := &http.Client{}
request, _ := http.NewRequest("POST",
"https://data.oxylabs.io/v1/queries",
bytes.NewBuffer(jsonValue),
)

request.SetBasicAuth(Username, Password)
response, _ := client.Do(request)

responseText, _ := ioutil.ReadAll(response.Body)
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.Threading.Tasks;

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

            var parameters = new
            {
                source = "gemini",
                prompt = "best supplements for better sleep",
                parse = true,
                geo_location = "United States",
                callback_url = "https://your-server.com/oxylabs-callback"
            };

            var client = new HttpClient();

            Uri baseUri = new Uri("https://data.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(System.Text.ASCIIEncoding.UTF8.GetBytes(authenticationString));
            requestMessage.Headers.Add("Authorization", "Basic " + base64EncodedAuthenticationString);

            var response = await client.SendAsync(requestMessage);
            var contents = await response.Content.ReadAsStringAsync();

            Console.WriteLine(contents);
        }
    }
}
```

{% endtab %}

{% tab title="Java" %}

```java
package org.example;

import okhttp3.*;
import org.json.JSONObject;

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() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("source", "gemini");
        jsonObject.put("prompt", "best supplements for better sleep");
        jsonObject.put("parse", true);
        jsonObject.put("geo_location", "United States");
        jsonObject.put("callback_url", "https://your-server.com/oxylabs-callback");

        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)
                .build();

        var mediaType = MediaType.parse("application/json; charset=utf-8");
        var body = RequestBody.create(jsonObject.toString(), mediaType);
        var request = new Request.Builder()
                .url("https://data.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": "gemini",
    "prompt": "best supplements for better sleep",
    "parse": true,
    "geo_location": "United States",
    "callback_url": "https://your-server.com/oxylabs-callback"
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**注意：** 所有 LLM 来源默认启用 JavaScript 渲染。您无需在请求负载中包含渲染参数。
{% endhint %}

使用以下方式提交作业 [**Push-Pull**](/products/cn/web-scraper-api/integration-methods/push-pull.md) 集成（包括 [批量查询](/products/cn/web-scraper-api/integration-methods/push-pull.md#batch-query)) 方法会立即返回作业 ID，而不是结果。一旦作业状态为 `done`，即可获取解析后的响应。参见 [**集成方式**](/api-targets/cn/llms-and-ai.md#integration-method) LLMs 和 AI 页面上的完整提交与检索流程。

### 请求参数

用于抓取 Gemini 的基本设置和自定义选项。

<table><thead><tr><th width="222">参数</th><th width="350.3333333333333">描述</th><th>默认值</th></tr></thead><tbody><tr><td><mark style="background-color:green;"><strong><code>source</code></strong></mark></td><td>设置爬虫目标。使用 <code>gemini</code>.</td><td>–</td></tr><tr><td><mark style="background-color:green;"><strong><code>prompt</code></strong></mark></td><td>要提交给 Gemini 的提示词或问题。必须少于 8000 个字符。</td><td>–</td></tr><tr><td><code>callback_url</code></td><td><strong>推荐。</strong> 作业完成后我们发送通知的 URL。 <a href="https://developers.oxylabs.io/products/web-scraper-api/integration-methods/push-pull"><strong>更多信息</strong></a><strong>.</strong></td><td>–</td></tr><tr><td><code>解析</code></td><td>设置为 <code>true</code> 用于结构化 JSON 数据。</td><td><code>false</code></td></tr><tr><td><code>geo_location</code></td><td>指定请求路由所在的国家/地区。 <a href="/products/cn/web-scraper-api/features/localization.md"><strong>更多信息</strong></a>.</td><td>–</td></tr><tr><td><code>browser_instructions</code></td><td>渲染 JavaScript 时的可选自定义浏览器指令。 <a href="/products/cn/web-scraper-api/features/js-rendering-and-browser-control.md#browser-instructions"><strong>更多信息</strong></a>.</td><td>–</td></tr></tbody></table>

\- 必填参数

## 结构化数据

通过 Push-Pull 结果端点获取任务后，网页爬虫API能够提取包含 Gemini 输出的 JSON 对象，从而提供有关结果页面各元素的结构化数据。

<details>

<summary><code>gemini</code> 结构化输出</summary>

```json
{
  "results": [
    {
      "job_id": "7470031540181837825",
      "status_code": 200,
      "url": "https://gemini.google.com/app/ca6b069d5af5c809",
      "content": {
        "prompt": "best supplements for better sleep",
        "response_text": "如果您辗转反侧，您绝对不是唯一一个。补充剂货架上摆满了声称能帮助您入睡的产品，但根据它们实际影响身体的方式，这些产品通常可分为几种不同类别。这里……",
        "markdown_text": "如果您辗转反侧，您绝对不是唯一一个。补充剂货架上摆满了声称能帮助您入睡的产品，但根据它们实际影响身体的方式，这些产品通常可分为几种不同类别。\n\n 这里……",
        "citations": [
          {
            "title": "Hartford HealthCare",
            "url": "https://hartfordhealthcare.org/about-us/news-press/news-detail?articleId=66180",
            "text": "这 3 种补充剂真的能改善您的睡眠吗？| Hartford HealthCare | CT",
            "description": "- 缬草根。这种草本助眠选择可能通过作用于大脑中的 GABA 受体发挥作用，与镁类似。\"但它并非没有副作用，\"……说。"
          },
          {
            "title": "BBC Good Food",
            "url": "https://www.bbcgoodfood.com/review/best-sleep-supplements#:~:text=It's%20easy%20to%20get%20enough,a%20role%20in%20sleep%20regulation.",
            "text": "2026 年最佳助眠补充剂——经过试用和测试 - BBC Good Food",
            "description": "通过饮食很容易摄入足量，但如果您想补充，NRV 约为 300mg，并且应选择已被证明能够……的甘氨酸镁。"
          },
          {
            "title": "PMC - NIH",
            "url": "https://pmc.ncbi.nlm.nih.gov/articles/PMC11082867/#:~:text=Melatonin%20is%20a%20hormone%20produced,promotes%20relaxation%20and%20reduced%20alertness.",
            "text": "关于改善睡眠质量的常见膳食补充剂的当前证据 - PMC - NIH",
            "description": "褪黑素是由大脑松果体产生的一种激素，在调节睡眠-觉醒周期中发挥关键作用。松果体开始……"
          },
          ...
        ],
        "parse_status_code": 12000
      }
    }
  ]
}
```

</details>

{% hint style="warning" %}
响应的组成可能会因查询是否来自 **desktop** 或 **mobile** 设备而有所不同。
{% endhint %}

### 输出数据字典

所有 LLM 目标返回相同的顶层 `作业` 和 `results[]` 封装。参见 [LLMs 和 AI](/api-targets/cn/llms-and-ai.md) 以查看完整的元数据参考。

下表展示了 Gemini 专用的 `results[].content` 字段：

<table><thead><tr><th width="140">字段名称</th><th width="427">描述</th><th>类型</th></tr></thead><tbody><tr><td><code>prompt</code></td><td>已提交的提示词。</td><td>字符串</td></tr><tr><td><code>raw</code></td><td>流式响应中的原始数据。</td><td>数组</td></tr><tr><td><code>response_text</code></td><td>Gemini 返回的纯文本响应。</td><td>字符串</td></tr><tr><td><code>markdown_text</code></td><td>Markdown 格式的完整响应。</td><td>字符串</td></tr><tr><td><mark style="background-color:yellow;"><code>citations</code></mark></td><td>响应中引用的来源。每个对象包含 <code>title</code>, <code>url</code>, <code>text</code>，以及 <code>description</code>.</td><td>数组</td></tr><tr><td><code>parse_status_code</code></td><td><code>12000</code> – 成功。否则，解析器未能提取部分或全部结构化字段。</td><td>整数</td></tr><tr><td><code>model</code></td><td>用于生成响应的 AI 模型。</td><td>字符串</td></tr></tbody></table>

– 条件返回，仅在内容出现在 LLM 响应中时返回。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://developers.oxylabs.io/api-targets/cn/llms-and-ai/gemini.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
