selenium工具类 - 文件名 seleniumkit.py
代码如下
from selenium import webdriverimport os
import timefrom selenium. webdriver. support. ui import WebDriverWait
from selenium. webdriver. support import expected_conditions as EC
from selenium. webdriver. common. by import Byfrom selenium. webdriver. chrome. service import Service
def seleniumOpenUrl ( initUrl) : chrome_options = webdriver. ChromeOptions( ) chrome_options. add_argument( '---ignore-certificate-errors-spki-list' ) chrome_options. add_argument( '--ignore-ssl-errors' ) chrome_options. add_argument( '--ignore-ssl-error' ) chrome_options. add_argument( 'log-level=2' ) chrome_options. add_experimental_option( 'useAutomationExtension' , False ) chrome_options. add_argument( "--disable-blink-features=AutomationControlled" ) path = os. path. join( os. getcwd( ) , 'chromedriver.exe' ) print ( 'chromePath:' , path) service = Service( executable_path= path) driver = webdriver. Chrome( options= chrome_options, service= service) driver. get( initUrl) driver. maximize_window( ) return driver
def seleniumOpenUrlHeadless ( initUrl) : chrome_options = webdriver. ChromeOptions( ) chrome_options. add_argument( '---ignore-certificate-errors-spki-list' ) chrome_options. add_argument( '--ignore-ssl-errors' ) chrome_options. add_argument( '--ignore-ssl-error' ) chrome_options. add_argument( 'log-level=2' ) chrome_options. add_experimental_option( 'useAutomationExtension' , False ) chrome_options. add_argument( "--disable-blink-features=AutomationControlled" ) path = os. path. join( os. getcwd( ) , 'chromedriver.exe' ) print ( 'chromePath:' , path) browser_locale = 'fr' chrome_options. add_argument( "--lang={}" . format ( browser_locale) ) chrome_options. add_argument( "--headless" ) chrome_options. add_argument( 'headless' ) service = Service( executable_path= path) driver = webdriver. Chrome( options= chrome_options, service= service) driver. get( initUrl) driver. maximize_window( ) return driver
测试打开百度 - test.py
from selenium. webdriver. support. ui import WebDriverWait
from selenium. webdriver. support import expected_conditions as EC
from selenium. webdriver. common. keys import Keys
from selenium. webdriver. common. by import By
from seleniumkit import * def openBaiDu ( ) : initUrl = "https://www.baidu.com/" driver = seleniumOpenUrl( initUrl) return driverif __name__ == "__main__" : openBaiDu( ) time. sleep( 10 )
打开百度的效果