如何在 SeleniumBase 中使用代理

使用带身份验证的代理配置 SeleniumBase,绕过各类限制,提升网页抓取成功率。
4 min read
如何在 SeleniumBase 中使用代理

SeleniumBase 旨在为在测试环境中运行 Selenium 实例提供封装。不过,它不仅仅是一个封装工具。SeleniumBase 允许我们使用带有身份验证的代理来运行 Selenium。

Selenium 原生代理问题

Selenium 对代理的支持并不完美。虽然可以通过 --proxy-server 参数传递代理给 Selenium,但它并不支持带有身份验证的代理。更糟糕的是,SeleniumWire 多年来一直是与 Selenium 搭配使用代理的首选方案,集成非常简单。然而,SeleniumWire 在一年多前就不再维护了,已经两年多没有更新。

SeleniumWire 弃用

开始使用

首先,我们需要安装 SeleniumBase 并编写一个测试用例。测试用例实际上是控制 Selenium 并为我们运行 webdriver 实例的。

安装

pip install seleniumbase

编写测试用例

下面是一个简单的测试用例。以下代码会向 IPinfo API 发送请求。一旦我们收到 JSON 响应,就会对其进行解析并将内容打印到控制台。

from seleniumbase import BaseCase
from selenium.webdriver.common.by import By
import json

class ProxyTest(BaseCase):
   def test_proxy(self):
        #go to the site
        self.driver.get("https://ipinfo.io/json")
      
        #load the json response
        location_info = json.loads(self.driver.find_element(By.TAG_NAME, "body").text)

        #iterate through the dict and print its contents
        for k,v in location_info.items():
            print(f"{k}: {v}")

运行测试用例

为了实际运行这段代码,我们需要运行测试。这里我们不会使用 python name_of_your_script.py,而是使用 pytest

不使用代理

如果你想在没有代理的情况下运行测试脚本,可以使用下面的命令:

pytest proxy_test.py -s

你会看到类似下面这样的输出:

=================================================== test session starts ===================================================
platform linux -- Python 3.10.12, pytest-8.3.4, pluggy-1.5.0
rootdir: /home/nultinator/clients/bright-data/seleniumbase-proxies
plugins: html-4.0.2, metadata-3.1.1, anyio-4.0.0, seleniumbase-4.34.6, ordering-0.6, rerunfailures-15.0, xdist-3.6.1
collected 1 item                                                                                                          

proxy_test.py ip: 23.28.108.255
hostname: d28-23-255-108.dim.wideopenwest.com
city: Westland
region: Michigan
country: US
loc: 42.3242,-83.4002
org: AS12083 WideOpenWest Finance LLC
postal: 48185
timezone: America/Detroit
readme: https://ipinfo.io/missingauth
.

==================================================== 1 passed in 1.01s ====================================================

代理配置

要使用代理,我们只需要使用 --proxy 标志并跟上代理的地址即可。格式如下:

--proxy=your_proxy_url:your_proxy_port

免费代理

下面的示例使用了一个免费代理。这个 IP 地址是 155.54.239.64,我们使用的端口是 80

--proxy=155.54.239.64:80

带身份验证的代理

带身份验证的代理使用方式相同。只需要在 URL 中包含用户名和密码即可。

proxy=<YOUR_USERNAME>:<YOUR_PASSWORD>@<PROXY_URL>:<PROXY_PORT>

最佳的带身份验证代理类型及供应商

在使用 Selenium 搭配身份验证代理时,最佳选择是住宅代理数据中心代理ISP代理,它们分别提供不同级别的匿名性和可靠性。住宅代理通过使用真实用户 IP,成功率最高,适合绕过反爬虫检测。数据中心代理速度更快、成本更低但更容易被检测到。ISP 代理结合了两者的优点,兼具速度与高可信度。

推荐供应商:

  • Bright Data – 行业领先的住宅、ISP 和数据中心代理,内置会话控制和地理定位功能。
  • Oxylabs – 提供覆盖全球的住宅代理和数据中心代理。
  • Smartproxy – 价格实惠的住宅代理,易于集成。
  • SOAX轮转代理,定价灵活。

对于SeleniumBase 抓取而言,Bright Data 的住宅代理最为可靠,确保高成功率并最大程度地减少封禁。

使用代理运行

下面的示例配置使用了 Bright Data 的代理。请确保将用户名、Zone 名称和密码替换为你自己的。

pytest proxy_test.py --proxy=brd-customer-<YOUR-USERNAME>-zone-<YOUR-ZONE-NAME>:<YOUR-PASSWORD>@brd.superproxy.io:33335 -s

当我们运行它时,会得到以下输出。从输出中可以看到,我们的位置已经发生了改变。

=================================================== test session starts ===================================================
platform linux -- Python 3.10.12, pytest-8.3.4, pluggy-1.5.0
rootdir: /home/nultinator/clients/bright-data/seleniumbase-proxies
plugins: html-4.0.2, metadata-3.1.1, anyio-4.0.0, seleniumbase-4.34.6, ordering-0.6, rerunfailures-15.0, xdist-3.6.1
collected 1 item                                                                                                          

proxy_test.py ip: 144.202.4.246
hostname: 144-202-4-246.lum-int.io
city: Piscataway
region: New Jersey
country: US
loc: 40.4993,-74.3990
org: AS20473 The Constant Company, LLC
postal: 08854
timezone: America/New_York
readme: https://ipinfo.io/missingauth
.

==================================================== 1 passed in 3.25s ====================================================

控制位置

使用我们的代理,你甚至可以指定自己的位置。只需要在代理中加入 country 标志即可。每个国家都有一个两位的国家代码,可以传递给代理。

pytest proxy_test.py --proxy=brd-customer-<YOUR-USERNAME>-zone-<YOUR-ZONE-NAME>:<YOUR-PASSWORD>[email protected]:33335 -s

当你使用 es(西班牙)作为国家代码时,你将通过位于西班牙的代理进行访问。可以通过以下输出进行验证:

=================================================== test session starts ===================================================
platform linux -- Python 3.10.12, pytest-8.3.4, pluggy-1.5.0
rootdir: /home/nultinator/clients/bright-data/seleniumbase-proxies
plugins: html-4.0.2, metadata-3.1.1, anyio-4.0.0, seleniumbase-4.34.6, ordering-0.6, rerunfailures-15.0, xdist-3.6.1
collected 1 item                                                                                                          

proxy_test.py ip: 176.119.14.158
city: Paracuellos de Jarama
region: Madrid
country: ES
loc: 40.5035,-3.5278
org: AS203020 HostRoyale Technologies Pvt Ltd
postal: 28860
timezone: Europe/Madrid
readme: https://ipinfo.io/missingauth
.

==================================================== 1 passed in 3.98s ====================================================

可以在这里查看我们的地理定位文档。

轮转代理

只需掌握 Python 的一些基本知识,你就可以创建一个相当不错的代理系统。下面的代码中,我们使用了国家代码列表,但它们也可以替换为实际的代理 IP。countries 中存放了国家代码,然后我们遍历它们,使用其中的每个国家代码运行一次代理测试。

  • us:美国
  • es:西班牙
  • il:以色列
  • gb:英国
import subprocess

#list of country codes
countries = [
    "us",
    "es",
    "il",
    "gb",
]

#iterate through the countries and make a shell command for each one
for country in countries:
    command = f"pytest proxy_test.py --proxy=brd-customer-<YOUR-USERNAME>-<YOUR-ZONE-NAME>-country-{country}:[email protected]:33335 -s"

    #run the shell command
    subprocess.run(command, shell=True)

你可以像运行普通 Python 文件一样运行它:

python rotate_proxies.py

运行后,你应该会看到类似下面的输出:

(Linux uses --headless by default. To override, use --headed / --gui. For Xvfb mode instead, use --xvfb. Or you can hide this info by using --headless / --headless2 / --uc.)
=================================================== test session starts ===================================================
platform linux -- Python 3.10.12, pytest-8.3.4, pluggy-1.5.0
rootdir: /home/nultinator/clients/bright-data/seleniumbase-proxies
plugins: html-4.0.2, metadata-3.1.1, anyio-4.0.0, seleniumbase-4.34.6, ordering-0.6, rerunfailures-15.0, xdist-3.6.1
collected 1 item                                                                                                          

proxy_test.py ip: 164.90.142.33
city: Clifton
region: New Jersey
country: US
loc: 40.8344,-74.1377
org: AS14061 DigitalOcean, LLC
postal: 07014
timezone: America/New_York
readme: https://ipinfo.io/missingauth
.

==================================================== 1 passed in 3.84s ====================================================
(Linux uses --headless by default. To override, use --headed / --gui. For Xvfb mode instead, use --xvfb. Or you can hide this info by using --headless / --headless2 / --uc.)
=================================================== test session starts ===================================================
platform linux -- Python 3.10.12, pytest-8.3.4, pluggy-1.5.0
rootdir: /home/nultinator/clients/bright-data/seleniumbase-proxies
plugins: html-4.0.2, metadata-3.1.1, anyio-4.0.0, seleniumbase-4.34.6, ordering-0.6, rerunfailures-15.0, xdist-3.6.1
collected 1 item                                                                                                          

proxy_test.py ip: 5.180.9.15
city: Madrid
region: Madrid
country: ES
loc: 40.4066,-3.6724
org: AS203020 HostRoyale Technologies Pvt Ltd
postal: 28007
timezone: Europe/Madrid
readme: https://ipinfo.io/missingauth
.

==================================================== 1 passed in 3.60s ====================================================
(Linux uses --headless by default. To override, use --headed / --gui. For Xvfb mode instead, use --xvfb. Or you can hide this info by using --headless / --headless2 / --uc.)
=================================================== test session starts ===================================================
platform linux -- Python 3.10.12, pytest-8.3.4, pluggy-1.5.0
rootdir: /home/nultinator/clients/bright-data/seleniumbase-proxies
plugins: html-4.0.2, metadata-3.1.1, anyio-4.0.0, seleniumbase-4.34.6, ordering-0.6, rerunfailures-15.0, xdist-3.6.1
collected 1 item                                                                                                          

proxy_test.py ip: 64.79.233.151
city: Tel Aviv
region: Tel Aviv
country: IL
loc: 32.0809,34.7806
org: AS9009 M247 Europe SRL
timezone: Asia/Jerusalem
readme: https://ipinfo.io/missingauth
.

==================================================== 1 passed in 3.36s ====================================================
(Linux uses --headless by default. To override, use --headed / --gui. For Xvfb mode instead, use --xvfb. Or you can hide this info by using --headless / --headless2 / --uc.)
=================================================== test session starts ===================================================
platform linux -- Python 3.10.12, pytest-8.3.4, pluggy-1.5.0
rootdir: /home/nultinator/clients/bright-data/seleniumbase-proxies
plugins: html-4.0.2, metadata-3.1.1, anyio-4.0.0, seleniumbase-4.34.6, ordering-0.6, rerunfailures-15.0, xdist-3.6.1
collected 1 item                                                                                                          

proxy_test.py ip: 185.37.3.107
city: London
region: England
country: GB
loc: 51.5085,-0.1257
org: AS9009 M247 Europe SRL
postal: E1W
timezone: Europe/London
readme: https://ipinfo.io/missingauth
.

==================================================== 1 passed in 2.90s ====================================================

可以看到,仅用少量的代码,我们就可以分别使用位于美国、西班牙、以色列和英国的代理。

结论

当进行网络爬取时,SeleniumBase 为 Selenium 拓展了许多其他人认为无法实现的功能。在本指南中,你学习了如何配置代理、控制地理位置以及如何轮转代理。这些技巧能够帮助你绕过绝大多数封锁机制。

通过 Bright Data 的行业领先代理服务,可以充分释放基于 Selenium 的爬取潜能。立即开始免费试用,体验大规模、高可靠性的数据采集流程!