最近由于自动化测试需要,要在docker里面安装chromedriver。Docker是基于python3.8.10的,安装也比较简单。
修改docker的源
镜像里的源还是ununtu的,为了速度,先修改为aliyun的源
cat <<EOF>/etc/apt/sources.list
deb http://mirrors.aliyun.com/debian/ buster main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ buster main non-free contrib
deb http://mirrors.aliyun.com/debian-security buster/updates main
deb-src http://mirrors.aliyun.com/debian-security buster/updates main
deb http://mirrors.aliyun.com/debian/ buster-updates main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ buster-updates main non-free contrib
deb http://mirrors.aliyun.com/debian/ buster-backports main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ buster-backports main non-free contrib
EOF
下载chrome
wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
安装chrome
apt-get install ./google-chrome-stable_current_amd64.deb -y
如果安装chrome出错,可以试一下以下命令安装:
apt-get --fix-broken install ./google-chrome-stable_current_amd64.deb
下载合适的chromedriver
wget -O /tmp/chromedriver.zip http://chromedriver.storage.googleapis.com/`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE`/chromedriver_linux64.zip
安装selenium的pip包
pip install selenium
测试代码
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
browser = webdriver.Chrome(chrome_options=options)
url = "https://www.baidu.com"
browser.get(url)
browser.save_screenshot("snapshot.png")
browser.quit()
可以看到当前路径下有“snapshot.png"图片,打开后,也是百度首页的截图。大工告成!