在无GUI环境下(headless模式)配置并使用Python+selenium+chromium/firefox的流程

本文介绍了在无图形用户界面(GUI)环境下,如何配置并使用Python+Selenium配合Chromium或Firefox进行自动化测试。主要探讨了两种方法:1) 使用Xvfb创建虚拟Xwindow输出,2) 利用浏览器内置的headless模式。详细步骤包括安装浏览器、Selenium、驱动程序,以及设置环境变量。文中还给出了Python脚本示例,展示了如何启用headless模式。
部署运行你感兴趣的模型镜像

Selenium

Selenium封装了能够进行浏览器自动化的一系列工具和库的一款自动化工具。Selenium提供了遵守W3C WebDriver specification的一个平台,并且该平台提供了能与当前市面上几乎所有浏览器兼容的接口。如果需要使用SeleniumAPI控制浏览器,只需要定义 Selenium WebDriver并下载相应浏览器的驱动程序(executable)即可。需要注意的是,该驱动程序需要位于系统路径(PATH环境变量)下,这样Selenuim才可以找得到这个程序。同时我们需要保证该驱动程序属性是可执行文件(可以利用chmod a+x chromedriver修改)

因为其良好的兼容性,Selenium现在被广泛用作自动化前端测的工具,或者用于驱动一些复杂的爬虫程序。

在headless环境中运行Selenium webdriver

默认情况下,WebDriver将会自动启动一个浏览器然后在该浏览器中运行脚本中指定的步骤,最后退出。但这种情况要求我们一定要有GUI输出。如果我们希望在一个无GUI的环境(如一台linux服务器)中通过命令行来执行我们的脚本,则需要进行一定配置。

首先我们需要安装Firefox或者Chromium浏览器。

$ sudo apt-get update
$ sudo apt-get install chromium-browser

或者

$ sudo apt-get update
$ sudo apt-get install firefox

其次我们需要安装Selenium。

$ sudo pip install selenium

最后我们需要下载相应浏览器的driver驱动文件并将其放在PATH路径下。

方法1:使用Xvfb创建虚拟Xwindow输出

首先我们需要安装xvfb(X windows virtual frame buffer)。运行如下命令:

$ sudo apt-get update
$ sudo apt-get install xvfb

然后我们需要启动Xvfb并指定一个输出端口号(本例中为54321)。

$ Xvfb :54321 -ac &

接着我们指定上一步选定的输出端口号作为DISPLAY环境变量。

$ export DISPLAY=:54321

最后我们就可以测试浏览器是否可以正常运行。

$ firefox

或者

$ chromium-browser

如果浏览器能够正常运行,不报错,则说明我们已经配置好了,可以用Ctrl-C退出。

现在我们就可以正常运行我们的Selenium WebDriver脚本了(这个脚本的代码甚至不需要任何改变!)。该方法的优势正在于此。配置好Xvfb之后,我们可以在该headless服务器的环境中运行任何WebDriver。

下面是一个Python+Selenium WebDriver脚本的简单例子。

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

def get_redurection_chain(url):
    """
    Given a url, return the urls in redirection chain and the length of the redirection chain.
    The redirection chain will be checked using selenium driven chrome browser and retrieved from
    browser log.

    :param url: the url that will be checked.
    :return: (
        length of redirection chain,
        a list of the urls in the redirection ordered based on the sequence they are visited,
    )
    """
    # landing_urls record origins->url->other intermedia urls->final_url
    landing_urls = list()
    landing_urls.append(url)

    curr_url = url

    capabilities = DesiredCapabilities.CHROME
    capabilities['loggingPrefs'] = {
        'performance': 'ALL',
    }

    driver = webdriver.Chrome(
        desired_capabilities=capabilities,
    )

    driver.get(url)

    for log in driver.get_log('performance'):
        log_entry = json.loads(log['message'])

        if 'redirectResponse' not in log_entry['message']['params']:
            continue
        if log_entry['message']['params']['redirectResponse']['url'] == curr_url:
            redirect_url = log_entry['message']['params']['request']['url']
            landing_urls.append(redirect_url)
            curr_url = redirect_url

    driver.close()

    return len(landing_urls), landing_urls

if __name__ == '__main__':
    get_redurection_chain('http://facebook.com/')

方法2: 使用浏览器自带的headless模式运行

事实上,从去年以来,Chrome和Firefox都提供了headless运行的选项。这一举动对于像是PhantomJS这样的轻量级headless浏览器产生了极大的冲击。

以Chromium(或者Chrome)为例,要指定Selenium脚本使用headless模式运行浏览器,只需要增加option即可。如下面例子所示。

这一方法的优势在于不需要进行任何额外配置即可在无GUI环境中运行Selenium脚本。但缺点在于该方法依赖对应浏览器提供相应的headless模式。

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('headless')

相应的,方法1例子中的程序将变为:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities


def get_redurection_chain(url):
    """
    Given a url, return the urls in redirection chain and the length of the redirection chain.
    The redirection chain will be checked using selenium driven chrome browser and retrieved from
    browser log.

    :param url: the url that will be checked.
    :return: (
        length of redirection chain,
        a list of the urls in the redirection ordered based on the sequence they are visited,
    )
    """
    # landing_urls record origins->url->other intermedia urls->final_url
    landing_urls = list()
    landing_urls.append(url)

    curr_url = url

    capabilities = DesiredCapabilities.CHROME
    capabilities['loggingPrefs'] = {
        'performance': 'ALL',
    }

    options = webdriver.ChromeOptions()
    options.add_argument('--ignore-certificate-errors')
    options.add_argument('headless')

    driver = webdriver.Chrome(
        desired_capabilities=capabilities,
        chrome_options=options,
    )

    driver.get(url)

    for log in driver.get_log('performance'):
        log_entry = json.loads(log['message'])

        if 'redirectResponse' not in log_entry['message']['params']:
            continue
        if log_entry['message']['params']['redirectResponse']['url'] == curr_url:
            redirect_url = log_entry['message']['params']['request']['url']
            landing_urls.append(redirect_url)
            curr_url = redirect_url

    driver.close()

    return len(landing_urls), landing_urls

if __name__ == '__main__':
    get_redurection_chain('http://facebook.com/')

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

<think>我们将在ARM架构的统信UOS上配置Chrome浏览器的Selenium自动化测试环境。主要步骤包括:1.安装匹配的Chrome浏览器2.下载对应架构和版本的ChromeDriver3.配置Python环境Selenium库4.编写调试测试脚本注意:统信UOSARM版与x86架构不同,需要特别注意驱动和浏览器的兼容性。步骤详解:1.确认系统架构和浏览器版本-执行命令:`uname-m`确认是ARM架构(如aarch64)-检查Chrome版本:`google-chrome--version`或 `chromium-browser --version`(取决于安装的浏览器)2.下载匹配的ChromeDriver-访问ChromeDriver下载页面:https://chromedriver.chromium.org/downloads-根据Chrome版本号选择对应的驱动版本(大版本号必须一致)-注意选择LinuxARM64版本(如chromedriver_linux64_arm.zip)3.安装配置驱动-解压下载的驱动包:`unzip chromedriver_linux64_arm.zip`-将驱动移动到系统路径:`sudo mvchromedriver /usr/local/bin/`-赋予执行权限:`sudochmod+x/usr/local/bin/chromedriver`4.安装Selenium库:`pip installselenium`5.编写测试脚本(解决常见问题):-处理驱动路径问题-处理浏览器二进制路径问题(统信UOS的Chrome可能不在默认路径)-处理可能的权限问题完整代码示例:</think>### ARM架构统信UOS配置Chrome自动化测试环境指南 #### 核心问题解决路径 $$ \text{成功配置} = \begin{cases} \text{架构匹配的ChromeDriver} \\ \text{正确的浏览器路径} \\ \text{Selenium服务配置} \end{cases} $$ --- ### 分步配置方案 #### 1. 安装ARM兼容的Chrome浏览器 ```bash # 确认系统架构 $ uname -m # 应输出 aarch64 # 下载ARM版Chrome(以最新稳定版为例) $ wget https://dl.google.com/linux/direct/google-chrome-stable_current_arm64.deb # 安装依赖及浏览器 $ sudo apt install ./google-chrome-stable_current_arm64.deb ``` #### 2. 获取匹配的ChromeDriver ```bash # 查看Chrome版本 $ google-chrome --version # Google Chrome 124.0.6367.78 # 下载对应版本驱动(访问官方匹配页面) $ CHROME_VERSION=124.0.6367 $ wget https://chromedriver.storage.googleapis.com/${CHROME_VERSION}/chromedriver_linux64_arm.zip # 解压安装驱动 $ unzip chromedriver_linux64_arm.zip $ sudo mv chromedriver /usr/local/bin/ $ sudo chmod +x /usr/local/bin/chromedriver ``` #### 3. Python环境配置 ```bash # 安装必要依赖 $ sudo apt install python3-pip # 安装Selenium库 $ pip install selenium webdriver-manager ``` #### 4. 完整测试脚本 ```python from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager import os def chrome_automation_test(): try: # 统信UOS特殊路径配置 chrome_path = "/opt/google/chrome/google-chrome" # ARM版默认路径 # 自动管理驱动版本 service = Service(ChromeDriverManager().install()) options = webdriver.ChromeOptions() options.binary_location = chrome_path # ARM架构特殊配置 if "aarch64" in os.uname().machine: options.add_argument("--no-sandbox") # ARM需禁用沙盒 options.add_argument("--disable-dev-shm-usage") driver = webdriver.Chrome(service=service, options=options) driver.get("https://www.baidu.com") print("页面标题:", driver.title) except Exception as e: print("测试失败:", str(e)) finally: driver.quit() if __name__ == "__main__": chrome_automation_test() ``` #### 5. 验证与调试 ```bash # 验证驱动兼容性 $ chromedriver --version # ChromeDriver 124.0.6367.78 # 常见错误处理 $ file /usr/local/bin/chromedriver # 应显示 ELF 64-bit LSB executable, ARM aarch64 $ ls -l /opt/google/chrome/google-chrome # 验证浏览器路径 ``` --- ### 关键配置说明表 | 配置项 | ARM架构要求 | 统信UOS默认值 | |--------|-------------|---------------| | 浏览器路径 | `/opt/google/chrome/google-chrome` | 通过`whereis google-chrome`验证[^1] | | 驱动类型 | `linux64_arm`版本 | 必须匹配Chrome主版本号 | | 必要参数 | `--no-sandbox` | ARM架构必须添加 | | 内存优化 | `--disable-dev-shm-usage` | 防止/dev/shm内存不足 | --- ### 最佳实践 1. **使用WebDriverManager自动管理版本** ```python # 自动下载匹配驱动 service = Service(ChromeDriverManager().install()) ``` 2. **无头模式优化** ```python options.add_argument("--headless=new") # 新版无头模式 options.add_argument("--disable-gpu") # ARM GPU加速问题 ``` 3. **解决证书问题** ```python # 统信UOS特殊证书配置 options.add_argument("--ignore-certificate-errors") options.add_argument("--allow-insecure-localhost") ``` 4. **性能优化参数** ```python options.add_argument("--disable-extensions") options.add_argument("--disable-software-rasterizer") options.add_argument("--disable-infobars") ``` > 注意:统信UOS的安全策略可能导致浏览器启动失败,需在控制中心>安全中心>开发者模式中启用"允许未知来源应用"[^2] --- ### 相关问题 1. 如何解决Selenium中的`SessionNotCreatedException: This version of ChromeDriver only supports Chrome version XXX`错误? 2. 在ARM架构下如何优化Chrome无头模式的执行效率? 3. 统信UOS系统更新后浏览器驱动失效如何处理? 4. 如何实现Chrome和Firefox双浏览器的跨平台兼容性测试? 5. 在无GUI的服务器环境中如何配置Chrome自动化测试
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

耀凯考前突击大师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值