XVFB实现selenium在linux上无界面运行安装篇

本文介绍如何在Linux环境下配置Selenium进行无界面浏览器测试,包括使用XVFB、Chrome及Firefox进行设置的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

selenium在linux上无界面运行,其实是非常简单的。具体的方法有使用HtmlUnitDriver或者PhantomJSDriver,有时间我会写写关于这两个东东的文章,其实基本和ChromeDriver 和FirefoxDriver是一样的。但是有些人或者会比较排斥他们说HtmlUnitDriver对JS支持不好,PhantomJSDriver估计也很少有人用,其实他是对Phantomjs的封装,对这些不做多过评论,我用下来感觉还好。

            还有另一种方法,就是使用XVFB, 有人说XVFB是什么,没听说过,没听说过就自己Google吧。

这里就主要是讲一下XVFB的安装使用。以chrome + ubuntu 和 firefox + centOS 为例子(chrome linux版好像是到6的时候就不支持centOS了, 都自带firefox )

一、 XVFB在Ubuntu上的安装(chrome)

1. 安装ubuntu(百度google安装步骤)

2. putty.exe 连接ubuntu

    安装openssh-server:sudo apt-get install openssh-server
    启动openssh-server:   sudo /etc/init.d/ssh start
    确认openssh-server是否启动:ps -e | grep ssh
    telnet ip 端口号

3. 安装oracle JDK6:(可跳过:自带penjdk-6-jre)
    $ remove openjdk:  sudo apt-get autoremove openjdk-6-jre
    $ sudo add-apt-repository ppa:webupd8team/java
    $ sudo apt-get update
    $ sudo apt-get install oracle-java6-installer
    $ sudo update-java-alternatives -s java-6-oracle

4. 装chrome:(自带firefox)
    http://www.ubuntuupdates.org/ppa/google_chrome
    wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
    sudo sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
    sudo apt-get update
    sudo apt-get install google-chrome-stable

5. 装xvfb 及各种:
       sudo apt-get update && sudo apt-get install -y xfonts-100dpi xfonts-75dpi xfonts-scalable xfonts-cyrillic xvfb x11-apps  imagemagick firefox google-chrome-stable

 

OK, 到这一步都装好了。

 

二、测试安装

putty连接Ubuntu运行下面命令:

1. 启动Xvfb服务

 

 Xvfb -ac :7 -screen 0 1280x1024x8  (注意这个是x, 不是* 哦)

 2.  启动firefox or chrome

export  DISPLAY=:7

/usr/bin/google-chrome-stable http://www.investopedia.com         //chrome 浏览www.investopedia.com

或者

export DISPLAY=:7

firefox http://www.investopedia.com                                              //firefox 浏览www.investopedia.com

 

如果运行完后,出现:

Xlib: extension "RANDR"  missing on display ":7"

我想说,you made it. 这是个无关紧要的信息,之前我试图解决掉它,没有成功。最后我在运行selenium脚本后,完全没有出现这个信息,脚本执行很正常,所以现在我把它当做是安装成功的信息。

 

当然运行selenium 脚本前总不能老是敲一遍这些命令,太麻烦了。

弄成一个服务,先 touch /etc/init.d/xvfb

脚本如下:

Java代码  收藏代码
  1. #! /bin/bash  
  2. if [ -z "$1" ]; then   
  3. echo "`basename $0` {start|stop}"  
  4. exit  
  5. fi  
  6.   
  7. case "$1" in  
  8. start)  
  9.       /usr/bin/Xvfb :7 -ac -screen 0 1024x768x8 &  
  10. ;;  
  11. stop)  
  12.       killall Xvfb  
  13. ;;  
  14. esac  

 

修改脚本权限,启动服务:

chmod +x /etc/init.d/xvfb
chkconfig xvfb on
service xvfb start

 

停止服务的话就是: service xvfb stop

完毕了。

 

 

三、Xvfb在CentsOS安装

Java代码  收藏代码
  1.  Install Xvfb with library:  
  2.   
  3.     yum install Xvfb  
  4.     yum -y install libXfont  
  5.     yum install xorg-x11-fonts*  
  6.   
  7.   
  8. touch /etc/init.d/xvfb with content:  
  9.   
  10. #!/bin/bash  
  11. #  
  12. # /etc/rc.d/init.d/xvfbd  
  13. #  
  14. # chkconfig: 345 95 28  
  15. # description: Starts/Stops X Virtual Framebuffer server  
  16. # processname: Xvfb  
  17. #  
  18.   
  19. . /etc/init.d/functions  
  20.   
  21. "${NETWORKING}" = "no" ] && exit 0  
  22.   
  23. PROG="Xvfb"  
  24. PROG_OPTIONS=":7 -ac -screen 0 1024x768x24"  
  25. PROG_OUTPUT="/tmp/Xvfb.out"  
  26.   
  27. case "$1" in  
  28.     start)  
  29.         echo -n "Starting : X Virtual Frame Buffer "  
  30.         $PROG $PROG_OPTIONS>>$PROG_OUTPUT 2>&1 &  
  31.         disown -ar  
  32.         /bin/usleep 500000  
  33.         status Xvfb & >/dev/null && echo_success || echo_failure  
  34.         RETVAL=$?  
  35.         if [ $RETVAL -eq 0 ]; then  
  36.             /bin/touch /var/lock/subsys/Xvfb  
  37.             /sbin/pidof -o  %PPID -x Xvfb > /var/run/Xvfb.pid  
  38.         fi  
  39.         echo  
  40.         ;;  
  41.     stop)  
  42.         echo -n "Shutting down : X Virtual Frame Buffer"  
  43.         killproc $PROG  
  44.         RETVAL=$?  
  45.         [ $RETVAL -eq 0 ] && /bin/rm -f /var/lock/subsys/Xvfb /var/run/Xvfb.pid  
  46.         echo  
  47.         ;;  
  48.     restart|reload)  
  49.         $0 stop  
  50.         $0 start  
  51.         RETVAL=$?  
  52.         ;;  
  53.     status)  
  54.         status Xvfb  
  55.         RETVAL=$?  
  56.         ;;  
  57.     *)  
  58.      echo $"Usage: $0 (start|stop|restart|reload|status)"  
  59.      exit 1  
  60. esac  
  61.   
  62. exit $RETVAL  
  63.   
  64. Registering in system and start:  
  65. chmod +x /etc/init.d/xvfb  
  66. chkconfig xvfb on  
  67. service xvfb start  
  68.   
  69. now  
  70.   
  71. export DISPLAY=:7 (actually you should add this to your etc/bashrc)  

 

selenium 脚本测试一下环境:

随便丢个简单的selenium 写的脚本到配制好的测试机子上运行,如果没有任何报错,说明环境就是配制Ok的。

 

参考资料:

http://rrroutes.blogspot.com/2013/04/settup-environment-for-selenium-tests.html

http://www.installationpage.com/selenium/how-to-run-selenium-headless-firefox-in-ubuntu/

http://ralf.schaeftlein.de/2012/05/26/running-headless-webdriver-based-selenium-junit-tests-inside-jenkins-under-ubuntu-linux/

https://gist.github.com/textarcana/5855427

http://stackoverflow.com/questions/17944234/xlib-extension-randr-missing-on-display-21-trying-to-run-headless-googl

<think>我们正在配置无图形界面的Linux服务器上的Selenium与Chrome无头模式。根据引用[1][2][3],关键步骤包括安装Chrome浏览器、ChromeDriver驱动、设置Selenium选项参数等。以下是完整方案:###步骤1:安装GoogleChrome```bash#添加官方源并安装稳定版Chromesudocurl-sS-o-https://dl-ssl.google.com/linux/linux_signing_key.pub|sudoapt-keyadd-sudosh-c'echo"deb[arch=amd64]http://dl.google.com/linux/chrome/deb/stablemain">>/etc/apt/sources.list.d/google-chrome.list'sudoapt-getupdatesudoapt-getinstall-ygoogle-chrome-stable```###步骤2:安装ChromeDriver(版本必须与Chrome匹配)```bash#获取Chrome版本CHROME_VERSION=$(google-chrome--version|awk'{print$3}')#下载对应版本的ChromeDriver(以Linux64位为例)wgethttps://chromedriver.storage.googleapis.com/$(curl-shttps://chromedriver.storage.googleapis.com/LATEST_RELEASE_$CHROME_VERSION)/chromedriver_linux64.zipunzipchromedriver_linux64.zipsudomvchromedriver/usr/local/bin/```###步骤3:安装PythonSelenium库```bashpip3installselenium```###步骤4:编写Python脚本(关键参数配置)根据引用[2][3],必须添加`--no-sandbox`和`--disable-dev-shm-usage`参数:```pythonfromseleniumimportwebdriveroptions=webdriver.ChromeOptions()options.add_argument('--headless')#无头模式options.add_argument('--no-sandbox')#解决root用户运行问题[^2]options.add_argument('--disable-dev-shm-usage')#避免共享内存不足[^3]options.add_argument('--window-size=1920,1080')#设置分辨率[^3]driver=webdriver.Chrome(options=options)driver.get("https://example.com")print(driver.title)driver.quit()```###参数说明表|启动参数|作用说明||--------------------------|-------------------------------------------------------------------------||`--headless`|无界面运行||`--no-sandbox`|禁用沙盒(解决root用户权限问题)[^2]||`--disable-dev-shm-usage`|避免`/dev/shm`分区内存不足(Docker常见问题)[^3]||`--window-size=1920,1080`|设置虚拟窗口大小(无头模式下默认800x600)|###常见问题解决1.**Chrome启动失败**:检查`--no-sandbox`参数和ChromeDriver版本匹配性2.**内存错误**:确认添加`--disable-dev-shm-usage`参数[^3]3.**元素定位失败**:无头模式需设置足够大的窗口尺寸以触发响应式布局>**注意**:在Docker容器中运行,需使用基础镜像`python:slim`并安装依赖:>```Dockerfile>RUNapt-getupdate&&apt-getinstall-ywgetunziplibglib2.0-0libnss3libgconf-2-4libfontconfig1>```§§相关问题§§1.如何解决SeleniumLinux服务器上出现的"Chromefailedtostart"错误?2.如何为ChromeDriver选择与浏览器匹配的版本?3.Selenium无头模式测试与有头模式测试有何差异?4.Docker容器中运行Selenium需要哪些额外配置?</think>### 在无图形界面的 Linux 服务器上配置 Selenium 与 Chrome 无头模式 以下是完整配置指南,结合引用[1][2][3]的关键要点: #### 1. **安装依赖环境** ```bash sudo apt update sudo apt install -y python3-pip unzip wget xvfb libnss3-dev libgconf-2-4 ``` #### 2. **安装 Chrome 浏览器** ```bash # 添加 Google Chrome 官方源 curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - sudo sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list' # 安装 Chrome sudo apt update sudo apt install -y google-chrome-stable # 验证安装 google-chrome --version # 应输出版本号 ``` #### 3. **安装 ChromeDriver(关键步骤)** ```bash # 获取匹配的 ChromeDriver 版本 CHROME_VERSION=$(google-chrome --version | awk '{print $3}') DRIVER_VERSION=$(curl -s "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_${CHROME_VERSION%.*}") # 下载并安装 wget https://chromedriver.storage.googleapis.com/$DRIVER_VERSION/chromedriver_linux64.zip unzip chromedriver_linux64.zip sudo mv chromedriver /usr/local/bin/ sudo chmod +x /usr/local/bin/chromedriver # 验证 chromedriver --version # 应输出匹配版本 ``` #### 4. **安装 Python 依赖** ```bash pip3 install selenium webdriver-manager ``` #### 5. **配置 Selenium 无头模式(核心代码)** ```python from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--headless") # 无头模式[^1] chrome_options.add_argument("--no-sandbox") # root用户必须添加[^2] chrome_options.add_argument("--disable-dev-shm-usage") # 避免内存问题[^3] chrome_options.add_argument("--window-size=1920,1080") # 设置分辨率[^2] chrome_options.add_argument("--disable-gpu") # GPU加速禁用 # 初始化浏览器 driver = webdriver.Chrome(options=chrome_options) # 示例使用 driver.get("https://example.com") print("页面标题:", driver.title) driver.save_screenshot("screenshot.png") # 保存截图验证 driver.quit() ``` #### 6. **常见问题解决** | 错误信息 | 解决方案 | |---------|----------| | `Chrome failed to start: exited abnormally` | 添加 `--no-sandbox` 参数[^2] | | `/dev/shm` 相关内存错误 | 添加 `--disable-dev-shm-usage`[^3] | | 元素定位失败 | 增加 `--window-size` 确保页面完全加载 | | 证书错误 | 添加 `--ignore-certificate-errors` | #### 7. **验证配置** 创建测试脚本 `test_selenium.py`: ```python from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--no-sandbox') driver = webdriver.Chrome(options=options) try: driver.get("https://www.google.com") print("成功加载页面:", driver.title) driver.save_screenshot("success.png") print("截图已保存") except Exception as e: print("运行失败:", str(e)) finally: driver.quit() ``` 运行测试: ```bash python3 test_selenium.py ``` ### 关键配置说明 1. **`--no-sandbox`**:Linux 服务器(尤其是 root 用户)必须添加,否则 Chrome 无法启动[^2] 2. **`--disable-dev-shm-usage`**:解决 Docker 或低内存环境中的 `/dev/shm` 错误[^3] 3. **版本匹配**:Chrome 浏览器与 ChromeDriver 版本必须严格匹配 4. **分辨率设置**:无头模式默认窗口尺寸小,需明确设置 `--window-size` > **最佳实践**:在 Docker 中使用,建议选择官方镜像 `selenium/standalone-chrome` 并添加上述参数
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值