以mac 為例 :
1. 安裝chrome驅動
2. 找到chrome驅動安裝位置,which chromedriver (下面腳本會用到該路徑)
1 # -*- coding: utf-8 -*- 2 from selenium import webdriver 3 from selenium.webdriver.chrome.options import Options 4 import time 5 6 # 創建一個參數對象,用來控制chrome以無界面模式打開 7 chrome_options = Options() 8 chrome_options.add_argument('--headless') 9 chrome_options.add_argument('--disable-gpu') 10 # 驅動路徑 11 path = "/usr/local/bin/chromedriver" 12 # 創建瀏覽器對象 13 browser = webdriver.Chrome(executable_path=path, chrome_options=chrome_options) # 參數添加 14 15 # 上網 16 url = 'http://www.baidu.com/' 17 browser.get(url) 18 time.sleep(3) 19 browser.maximize_window() 20 browser.save_screenshot('baidu.png') # 捕獲(截屏)保存 21 22 browser.quit()
無頭瀏覽器搭建方式
Windows上部署無界面
1.Seleinum
2.谷歌瀏覽器Chrome
3.谷歌瀏覽器引擎Chromedriver
注意事項:
1. Chrome的版本要與Chromedriver的版本一致,否則不穩
2. Chrome最好用官方的,安裝官方的Chrome,用默認的安裝方式
2.1 安裝selenium
pip
install
selenium
2.2 安裝chrome
官網地址:
https://cloud.google.com/chrome-enterprise/browser/download/
注:谷歌瀏覽器不許你下載指定的版本
2.3 安裝Chromedirver
鏡像地址:
https://npm.taobao.org/mirrors/chromedriver/
2.4 查看自己Chrome的版本
在瀏覽器中輸入:chrome://version/
2.4.2 下載對應版本的Chromedriver
在Chromedriver的下載地址中:
沒有版本號完全一致的,只能找個差不多的,我測試后發現這兩個搭配沒問題
2.4.3 把Chromedriver放置在Chrome文件夾中
默認安裝路徑:C:⧵Program Files (x86)⧵Google⧵Chrome⧵Application
2 Mac上部署無界面
參考上面Windows的部署方式下載Chrome Mac版本的瀏覽器與Mac版的Chromedriver
將Chromedriver放在 /usr/local/bin中即可
3 Centos7 部署無界面
3.1 下載並安裝Chrome
wget
https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
yum
install
./google-chrome-stable_current_x86_64.rpm
3.2 安裝Chromedriver
3.2.1 查看Chrome版本
google-chrome
--version
3.3.2 下載與Chrome版本對應的Chromedriver
網址: https://npm.taobao.org/mirrors/chromedriver/
將chromdriver放在/usr/bin中
3.2.3 配置執行權限
終端
sudo
chmod
+x
chromedriver
4. 通過selenium啟動chrome
代碼
from
selenium
import
webdriver
#
實例化driver
driver
=
webdriver.Chrome(
executable_path='C:\Program
Files
(x86)\Google\Chrome\Application\chromedriver.exe',
#
Windows需要加exe
cutable_path,而Mac和Linux不用
)
driver.get('http://www.baidu.com')