先来一段代码,大家看一下:
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 默认下载目录