# 代理位置

使用 `geo_location` 参数选择代理服务器的位置。这样可以让你像从另一个国家浏览一样抓取数据。&#x20;

<details>

<summary>支持的 geo_location 值列表</summary>

```
奥兰群岛
阿富汗
阿尔巴尼亚
阿尔及利亚
美属萨摩亚
安道尔
安哥拉
安圭拉
南极洲
安提瓜和巴布达
阿根廷
亚美尼亚
阿鲁巴
澳大利亚
奥地利
阿塞拜疆
巴哈马
巴林
孟加拉国
巴巴多斯
白俄罗斯
比利时
伯利兹
贝宁
百慕大
不丹
玻利维亚（多民族国）
博内尔、圣尤斯特歇斯和萨巴
波斯尼亚和黑塞哥维那
博茨瓦纳
布韦岛
巴西
英属印度洋领地
文莱达鲁萨兰国
保加利亚
布基纳法索
布隆迪
佛得角
柬埔寨
喀麦隆
加拿大
开曼群岛
中非共和国
乍得
智利
中国
圣诞岛
科科斯（基林）群岛
哥伦比亚
科摩罗
刚果
刚果民主共和国
库克群岛
哥斯达黎加
科特迪瓦
克罗地亚
古巴
库拉索
塞浦路斯
捷克
丹麦
吉布提
多米尼克
多米尼加共和国
厄瓜多尔
埃及
萨尔瓦多
赤道几内亚
厄立特里亚
爱沙尼亚
斯威士兰
埃塞俄比亚
福克兰群岛 [马尔维纳斯]
法罗群岛
斐济
芬兰
法国
法属圭亚那
法属波利尼西亚
法属南部领地
加蓬
冈比亚
格鲁吉亚
德国
加纳
直布罗陀
希腊
格陵兰
格林纳达
瓜德罗普
关岛
危地马拉
根西岛
几内亚
几内亚比绍
圭亚那
海地
赫德岛和麦克唐纳群岛
圣座
洪都拉斯
香港
匈牙利
冰岛
印度
印度尼西亚
伊朗（伊斯兰共和国）
伊拉克
爱尔兰
马恩岛
以色列
意大利
牙买加
日本
泽西岛
约旦
哈萨克斯坦
肯尼亚
吉里巴斯
韩国
科威特
吉尔吉斯斯坦
老挝人民民主共和国
拉脱维亚
黎巴嫩
莱索托
利比里亚
利比亚
列支敦士登
立陶宛
卢森堡
澳门
马达加斯加
马拉维
马来西亚
马尔代夫
马里
马耳他
马绍尔群岛
马提尼克
毛里塔尼亚
毛里求斯
马约特
墨西哥
密克罗尼西亚联邦
摩尔多瓦共和国
摩纳哥
蒙古
黑山
蒙特塞拉特
摩洛哥
莫桑比克
缅甸
纳米比亚
瑙鲁
尼泊尔
荷兰
新喀里多尼亚
新西兰
尼加拉瓜
尼日尔
尼日利亚
纽埃
诺福克岛
北马里亚纳群岛
挪威
阿曼
巴基斯坦
帕劳
巴勒斯坦国
巴拿马
巴布亚新几内亚
巴拉圭
秘鲁
菲律宾
皮特凯恩群岛
波兰
葡萄牙
波多黎各
卡塔尔
北马其顿共和国
留尼汪
罗马尼亚
俄罗斯
卢旺达
圣巴泰勒米
圣赫勒拿、阿森松和特里斯坦-达库尼亚
圣基茨和尼维斯
圣卢西亚
圣马丁（法属部分）
圣皮埃尔和密克隆
圣文森特和格林纳丁斯
萨摩亚
圣马力诺
圣多美和普林西比
沙特阿拉伯
塞内加尔
塞尔维亚
塞舌尔
塞拉利昂
新加坡
荷属圣马丁（荷兰部分）
斯洛伐克
斯洛文尼亚
所罗门群岛
索马里
南非
南乔治亚和南桑威奇群岛
南苏丹
西班牙
斯里兰卡
苏丹
苏里南
斯瓦尔巴和扬马延
瑞典
瑞士
叙利亚阿拉伯共和国
中国台湾省
塔吉克斯坦
坦桑尼亚联合共和国
泰国
东帝汶
多哥
托克劳
汤加
特立尼达和多巴哥
突尼斯
土耳其
土库曼斯坦
特克斯和凯科斯群岛
图瓦卢
乌干达
乌克兰
阿拉伯联合酋长国
英国
美国
美属小离岛
乌拉圭
乌兹别克斯坦
瓦努阿图
委内瑞拉（玻利瓦尔共和国）
越南
英属维尔京群岛
美属维尔京群岛
瓦利斯和富图纳
西撒哈拉
也门
赞比亚
津巴布韦
```

</details>

{% hint style="warning" %}
`geo_location` parameter 在以下情况下的功能不同 [**SERP**](https://developers.oxylabs.io/documentation/cn/zhua-qu-jie-jue-fang-an/web-scraper-api/features/localization/serp-localization) 和 [**电商**](https://developers.oxylabs.io/documentation/cn/zhua-qu-jie-jue-fang-an/web-scraper-api/features/localization/e-commerce-localization) 本地化。请在各自章节中阅读更多信息。
{% endhint %}

### 请求示例

此示例使用德国的代理检索产品页面。

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

```shell
curl 'https://realtime.oxylabs.io/v1/queries' \
--user 'USERNAME:PASSWORD' \
-H 'Content-Type: application/json' \
-d '{
        "source": "universal",
        "url": "https://sandbox.oxylabs.io/products/1",
        "geo_location": "Germany"
    }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
from pprint import pprint


# 构建负载。
payload = {
    'source': 'universal',
    'url': 'https://sandbox.oxylabs.io/products/1',
    'geo_location': 'Germany',
}

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

# 这将返回带有结果的 JSON 响应，而不是包含作业状态和结果 URL 的响应。
# JSON 响应包含结果。
pprint(response.json())
```

{% endtab %}

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

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

const username = "USERNAME";
const password = "PASSWORD";
const body = {
    source: "universal",
    url: "https://sandbox.oxylabs.io/products/1",
    geo_location: "Germany",
};

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=universal&url=https%3A%2F%2Fsandbox.oxylabs.io%2Fproducts%2F1&geo_location=Germany&access_token=12345abcde
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$params = array(
    'source' => 'universal',
    'url' => 'https://sandbox.oxylabs.io/products/1',
    'geo_location' => 'Germany',
);

$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"

	payload := map[string]interface{}{
		"source":       "universal",
		"url":          "https://sandbox.oxylabs.io/products/1",
		"geo_location": "Germany",
	}

	jsonValue, _ := json.Marshal(payload)

	client := &http.Client{}
	request, _ := http.NewRequest("POST",
		"https://realtime.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 = "universal",
                url = "https://sandbox.oxylabs.io/products/1",
                geo_location = "Germany"
            };

            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(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;
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() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("source", "universal");
        jsonObject.put("url", "https://sandbox.oxylabs.io/products/1");
        jsonObject.put("geo_location", "Germany");

        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": "universal", 
    "url": "https://sandbox.oxylabs.io/products/1",
    "geo_location": "Germany"
}
```

{% 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) 集成，请参阅 [**集成方法**](https://developers.oxylabs.io/documentation/cn/zhua-qu-jie-jue-fang-an/web-scraper-api/integration-methods) 部分。

### 会话

你可以通过包含 `session_id` 参数强制多个请求使用相同的代理 IP 地址。将会话 ID 设置为任意字母数字字符串（例如， `abc123`），所有使用该会话 ID 的爬取任务都会使用相同的 IP。这在与 [自定义 Cookie](https://developers.oxylabs.io/documentation/cn/zhua-qu-jie-jue-fang-an/web-scraper-api/http-context-and-job-management/headers-cookies-method#custom-cookies).

结合时对会话管理很有用。

```json
{
    "source": "universal",
    这是一个示例：
    "geo_location": "Germany",
    "url": "https://sandbox.oxylabs.io/products",
}
```


---

# 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/features/localization/proxy-location.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.
