首页 / 帮助文档 / Python 怎么接移动代理(4G/5G)

Python 怎么接移动代理(4G/5G)

Using a Mobile Proxy in Python

requests · httpx · Selenium · Playwright · 粘性会话 · 报错排查 · 2026-11-27 更新
requests · httpx · Selenium · Playwright · sticky sessions · error playbook · updated 27 November 2026

移动代理和住宅代理用的是同一个 HTTP / SOCKS5 隧道,区别在出口。代码上真正要改的只有一件事:出口是怎么选的——国家、城市、会话活多久,以及一个 IP 可能同时在给真实手机用。这一页的代码抄一次就能长期用。

网关与账号格式

连 mobile.iplight.net:1086(备用 mobile-us.iplight.net:1086),用控制台里的子账号用户名和密码。地区的信息不写在 host 上,而是编码在用户名里:

<uid>-<authname>:<authpwd>-<region>[-session][-5m|1h]
片段含义
uid-authname子账号的用户 ID 与认证名,从控制台复制
authpwd子账号密码
regionglobal 表示任意出口;或具体地区 token,如 US_California_city_LosAngeles
-session可选。开启粘性会话,不写则每个请求换 IP
-5m / -1h可选。粘性时长,不写默认 5 分钟

地区 token 用下划线连接,格式是国家_州_城市_名称。token 写错会直接报错,不会悄悄回退到别的国家——买移动代理本来就是为了地理位置准确,静默回退是最坏的行为。

requests:最小可用示例

import requests

USER = "10001-abc123"
PWD  = "pass456"
EXIT = "US_California_city_LosAngeles"          # 或 "global"

proxy = "http://%s:%s-%s@mobile.iplight.net:1086" % (USER, PWD, EXIT)

r = requests.get("https://api.ipify.org?format=json",
                 proxies={"http": proxy, "https": proxy}, timeout=30)
print(r.json())      # {"ip": "..."} 运营商 IP,不是你的本机 IP

写更多代码之前先验两件事:返回的 IP 不是你自己的;这个 IP 的 ASN 属于移动运营商而不是机房。第二件事用 https://ipinfo.io/<ip>/json 看 org 字段——里面出现运营商名字,才是真的移动出口。

httpx,含异步

import httpx, asyncio

PROXY = "http://10001-abc123:pass456-global@mobile.iplight.net:1086"

# 同步
with httpx.Client(proxy=PROXY, timeout=30) as c:
    print(c.get("https://api.ipify.org").text)

# 异步,20 并发
async def main():
    async with httpx.AsyncClient(proxy=PROXY, timeout=30,
                                 limits=httpx.Limits(max_connections=20)) as c:
        rs = await asyncio.gather(*[c.get("https://api.ipify.org") for _ in range(20)])
        return [r.text for r in rs]

用 global 且不带 session 时,每个请求走不同手机,20 个返回里应该是多个 IP。如果全一样,要么用户名里还带着 session,要么 CDN 边缘把连接钉死了——先查用户名。

Selenium

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

opts = Options()
opts.add_argument("--proxy-server=http://mobile.iplight.net:1086")
driver = webdriver.Chrome(options=opts)
driver.get("https://api.ipify.org")
print(driver.find_element("tag name", "body").text)

Chrome 的 --proxy-server 不接受 user:pass@host 这种带凭据的写法。两个干净的做法:本地起一个中转(如 gost、mitmproxy)替请求补上 Proxy-Authorization 头;或者开 IP 白名单子账号,把跑批机器的出口 IP 加白,就不用带密码。

Playwright

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    b = p.chromium.launch(proxy={
        "server":   "http://mobile.iplight.net:1086",
        "username": "10001-abc123",
        "password": "pass456-US_California_city_LosAngeles-session-1h",
    })
    page = b.new_context().new_page()
    page.goto("https://api.ipify.org")
    print(page.inner_text("body"))
    b.close()

Playwright 把 server 和凭据分开传,所以不需要中转。整条后缀链放在 password 里——地区和会话 token 都长在这儿。

粘性会话:一段时间内固定一个 IP

加 -session 再选时长。同一个用户名在窗口内一直返回同一个出口,直到窗口结束或运营商把手机切走:

# 5 分钟(默认)
http://10001-abc123:pass456-US_California_city_LosAngeles-session@mobile.iplight.net:1086

# 1 小时
http://10001-abc123:pass456-US_California_city_LosAngeles-session-1h@mobile.iplight.net:1086

需要在请求之间保持状态时用粘性:登录流程、多步下单、购物车、把会话绑在 IP 上的分页。每个请求互不相干时用轮换:查价格、查排名、单页采集。

流量是怎么被烧掉的

移动代理按预付流量计费,双向计量,1 GB = 1000 MB。账单看的是搬了多少字节,不是发了多少请求,所以真正能省的是这几处:

报错排查表

现象原因处理
407 Proxy Authentication Required用户名密码错,或后缀链写坏了从控制台重新复制;确认地区、-session、时长三者顺序正确
429 或连接被拒并发超过子账号上限调低 max_connections;把任务拆到多个子账号
每个请求都是同一个 IP用户名里还有 session,或连接被 keep-alive 复用去掉 -session;测轮换时关闭连接复用
国家不对token 大小写错或中间带空格用控制台地区列表里的原始 token
首字节很慢运营商无线链路延迟移动网络本来就这样,150–600 ms 正常,调大超时而不是反复重试

什么时候不该用移动代理

移动代理每 GB 比住宅贵,速度也更慢,因为流量真的走了一趟无线网络。如果目标并不需要运营商 ASN——普通比价、目录采集、桌面端广告验证——动态住宅 $1.20/GB 更便宜也更快。移动代理的价值集中在注册登录、只有 App 才返回的接口,以及平台会判断“请求背后是不是一台真手机”的场景。

常见问题

-session-5m 和 -session-1h 有什么区别?

两者都固定出口 IP,区别是运营商保留多久。5 分钟适合一次登录或一张短表单;1 小时适合下单、分页、App 会话。窗口结束后手机会被切换,IP 可能变。

支持 SOCKS5 吗?

支持。用 socks5h:// 而不是 socks5://,让 DNS 在出口侧解析——否则目标站会看到解析地与出口地不一致,地理定位就露了。

为什么每次请求 IP 都不变?

要么用户名里还带着 -session,要么 HTTP 客户端在复用与网关的 keep-alive 连接。测轮换时,每个请求开新连接。

能同时跑很多异步请求吗?

可以,上限看子账号并发。建议从 10–20 并发起,观察有没有 429;移动网关比机房严格,因为每个出口是一台真实手机。

流量怎么算?

预付套餐,双向计量,统一按 1 GB = 1000 MB,与上游口径一致。控制台能看到每个子账号的剩余额度。

1 TB 套餐 $2.00/GB,够把一个流程跑通再决定上量。额度不过期。

注册账号

A mobile proxy is not a different protocol from a residential proxy — it is the same HTTP or SOCKS5 tunnel with a different exit. What changes in your code is how the exit is selected: the country and city, the session lifetime, and the fact that one IP can be shared with real handsets at the same moment. This page is the code you copy once and keep.

Gateway and credential format

Connect to mobile.iplight.net:1086 (backup mobile-us.iplight.net:1086) with the sub-account username and password from the console. The exit is encoded in the username, not in the host:

<uid>-<authname>:<authpwd>-<region>[-session][-5m|1h]
PartMeaning
uid-authnameYour sub-account user id and auth name, copied from the console
authpwdSub-account password
regionglobal for any exit, or a location token such as US_California_city_LosAngeles
-sessionOptional. Turns on a sticky session instead of per-request rotation
-5m / -1hOptional. Sticky lifetime; omit for the default 5 minutes

Region tokens use underscores and read country_state_city_<name>. If a token is rejected the request fails rather than quietly falling back to another country — which is what you want when geo accuracy is the reason you bought mobile in the first place.

requests: the minimal working call

import requests

USER = "10001-abc123"
PWD  = "pass456"
EXIT = "US_California_city_LosAngeles"          # or "global"

proxy = "http://%s:%s-%s@mobile.iplight.net:1086" % (USER, PWD, EXIT)

r = requests.get("https://api.ipify.org?format=json",
                 proxies={"http": proxy, "https": proxy}, timeout=30)
print(r.json())      # {"ip": "..."} - a carrier IP, not your own

Two things to verify before writing more code: the IP returned by api.ipify.org is not your own, and its ASN belongs to a mobile carrier rather than a hosting provider. Check the second one with https://ipinfo.io/<ip>/json — an org field containing a telecom name is the real signal that you bought mobile, not residential.

httpx, including async

import httpx, asyncio

PROXY = "http://10001-abc123:pass456-global@mobile.iplight.net:1086"

# sync
with httpx.Client(proxy=PROXY, timeout=30) as c:
    print(c.get("https://api.ipify.org").text)

# async, 20 concurrent requests
async def main():
    async with httpx.AsyncClient(proxy=PROXY, timeout=30,
                                 limits=httpx.Limits(max_connections=20)) as c:
        rs = await asyncio.gather(*[c.get("https://api.ipify.org") for _ in range(20)])
        return [r.text for r in rs]

With global and no session suffix every request leaves through a different handset, so the 20 replies should contain a mix of IPs. If they are all identical, you are either reusing a sticky username or the target is behind a CDN edge that pins connections — check the username first.

Selenium

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

opts = Options()
opts.add_argument("--proxy-server=http://mobile.iplight.net:1086")
driver = webdriver.Chrome(options=opts)

# Selenium has no proxy-auth field: inject the credential header instead
driver.execute_cdp_cmd("Network.enable", {})
driver.execute_cdp_cmd("Network.setExtraHTTPHeaders", {"headers": {}})
driver.get("https://api.ipify.org")

# preferred: authenticated proxy via a Chrome extension or an upstream
# unauthenticated local port (e.g. a tiny mitmproxy/gost hop)

Chrome cannot take user:pass@host in --proxy-server. The two clean options are a local relay that adds the Proxy-Authorization header, or an IP-whitelisted sub-account so no credential is needed. Ask support to whitelist your egress IP if you plan to drive a browser fleet.

Playwright

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    b = p.chromium.launch(proxy={
        "server":   "http://mobile.iplight.net:1086",
        "username": "10001-abc123",
        "password": "pass456-US_California_city_LosAngeles-session-1h",
    })
    ctx = b.new_context()
    page = ctx.new_page()
    page.goto("https://api.ipify.org")
    print(page.inner_text("body"))
    b.close()

Playwright splits server and credential, so no relay is needed. Put the whole suffix chain in the password — that is where the region and session tokens live.

Sticky sessions: hold one IP for a while

Add -session plus an optional lifetime. The same username keeps returning the same exit until the window expires or the carrier rotates the handset:

# 5 minutes (default)
http://10001-abc123:pass456-US_California_city_LosAngeles-session@mobile.iplight.net:1086

# 1 hour
http://10001-abc123:pass456-US_California_city_LosAngeles-session-1h@mobile.iplight.net:1086

Use sticky when state must survive between requests: a login flow, a multi-step checkout, a cart, or pagination on a site that binds the session to the IP. Use rotation when each request is independent — price lookups, SERP checks, single product pages.

What actually burns your gigabytes

Mobile is sold as prepaid traffic, metered 1 GB = 1000 MB in both directions. The bill is driven by bytes moved, not by requests, so these are the levers that matter:

Error playbook

SymptomCauseFix
407 Proxy Authentication RequiredUsername or password wrong, or the suffix chain is malformedRe-copy credentials from the console; check that region, -session and lifetime appear in that order
429 or connection refusedConcurrency above what the sub-account allowsLower max_connections; spread work across sub-accounts
Same IP on every requestSticky suffix still in the username, or a keep-alive connectionDrop -session; disable connection reuse for rotation tests
Country wrongToken spelled with spaces or wrong caseUse the exact token from the console location list
Slow first byteCarrier radio latencyNormal for mobile: 150–600 ms is expected; raise timeouts rather than retrying

When mobile is the wrong tool

Mobile IPs cost more per gigabyte than residential and are slower, because the traffic really does cross a radio network. If the target does not need a carrier ASN — ordinary price monitoring, catalogue scraping, ad verification on desktop pages — dynamic residential at $1.20/GB is cheaper and faster. Mobile earns its price on sign-up and sign-in flows, app-only endpoints, and anything where the platform checks whether a real phone is behind the request.

Frequently asked questions

What is the difference between -session-5m and -session-1h?

Both keep the exit IP fixed; the difference is how long the carrier holds it. 5 minutes suits a login or a short form; 1 hour suits a checkout, pagination or an app session. After the window the handset may rotate and you get a new IP.

Does SOCKS5 work?

Yes. Use socks5h:// rather than socks5:// so DNS is resolved at the exit instead of locally — otherwise the target sees a resolver mismatch and the geo pin leaks.

Why is my exit IP not changing between requests?

Either the username still carries -session, or your HTTP client is reusing a keep-alive connection to the gateway. For rotation tests, open a fresh connection per request.

Can I run many async requests at once?

Yes, bounded by the sub-account concurrency in the console. Start at 10–20 concurrent connections and watch for 429s; mobile gateways are less forgiving than datacenter ones because each exit is a physical handset.

How is mobile traffic counted?

Prepaid packages, metered 1 GB = 1000 MB in both directions, always on the 1000-based scale so the console and our upstream agree. Remaining quota is visible per sub-account.

1 TB at $2.00/GB is enough to validate a flow before committing to volume. Quota never expires between purchases.

Create an account

更多文档 IPLight 帮助文档中心 · 开发者文档 · support@iplight.net · 返回官网