先來一段代碼,大家看一下:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
class ChromeTool:
debug = False
driver = None
chrome_opt = Options() # 創建參數設置對象.
def __init__(self):
self.chrome_opt.add_argument('--no-sandbox')
self.chrome_opt.add_argument('--window-size=1366,768') # 設置窗口大小, 窗口大小會有影響.
def open_chrome(self, headless=False, download_path=''):
if headless:
self.chrome_opt.add_argument('--headless') # 無界面化.
self.chrome_opt.add_argument('--disable-gpu') # 配合上面的無界面化.
# 設置瀏覽器的下載目錄
if len(download_path) != 0:
self.chrome_opt.add_argument('download.default_directory=' + download_path)
# 創建Chrome對象並傳入設置信息.
chromedriver_path = Config.chrome_driver
if os.path.exists(chromedriver_path):
self.driver = webdriver.Chrome(executable_path=chromedriver_path, options=self.chrome_opt)
else:
self.driver = webdriver.Chrome(options=self.chrome_opt)
def close_chrome(self):
self.driver.close()
self.driver.quit()
大家看到上面提到了幾個參數:
1. --no-sandbox 沙箱
2. --window-size 配置CHROME的窗口大小
3 --headless 不想彈出 界面,後臺操作CHROME
4 --disable-gpu 關閉GPU
5. download.default_directory 默認下載目錄