Selenium操作Chrome

admin
2022-12-06 / 0 评论 / 2 阅读 / 正在检测是否收录...
import os,platform,time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ChromeOptions


sys_platform = platform.platform().lower()
if "windows" in sys_platform:
    binary_location = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
    executable_path = "C:\\chromedriver.exe"
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
elif "macos" in sys_platform:
    binary_location = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    executable_path = os.path.expanduser('~') + '/Documents/chromedriver'
    user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'

defaults = './Profile'

option = ChromeOptions()
option.binary_location = binary_location
option.add_experimental_option('useAutomationExtension', False)
option.add_experimental_option("excludeSwitches", ['enable-automation'])
option.add_argument('--lang=zh-cn')
option.add_argument('--disable-translate')
option.add_argument(f'--window-position={100},{100}')
option.add_argument(f'--user-data-dir={defaults}')
option.add_argument(f'user-agent={user_agent}')
option.add_argument('--disable-gpu')
option.add_argument('--ignore-certificate-errors')
option.add_argument('--ignore-ssl-errors')

bro = webdriver.Chrome(executable_path=executable_path,options=option)
bro.set_window_size(1024,768)
bro.implicitly_wait(8)
bro.get('https://www.baidu.com/')

time.sleep(5)

bro.close()
bro.quit()
0

评论 (0)

取消