python - selenium + Edge

1. 安装相关库和下载相关文件

pip3 install selenium
pip3 install msedge-selenium-tools

https://developer.microsoft.com/zh-cn/microsoft-edge/tools/webdriver/ 下载msedgedriver.exe,可在edge帮助查看当前edge的版本号,下载对应版本即可

2. 代码

from selenium import webdriver
from msedge.selenium_tools import Edge, EdgeOptions
from selenium.webdriver.common.action_chains import ActionChains
from retry import retry

# 使用xpath来定位元素
@retry(tries=3, delay=1) # 重试3次, 间隔1s
def try_find_element(xpath):
    tmp = driver.find_element_by_xpath(xpath)
    return tmp

@retry(tries=3, delay=1)
def try_click_element(xpath):
    tmp = driver.find_element_by_xpath(xpath)
    tmp.click()

@retry(tries=3, delay=1)
def try_click_elements(xpath, num):
    tmp = driver.find_elements_by_xpath(xpath)[num]
    tmp.click()

@retry(tries=3, delay=1)
def try_click_box(xpath, flag):
    tmp = driver.find_element_by_xpath(xpath)
    if flag == tmp.is_selected():
        tmp.click()

@retry(tries=3, delay=1)
def try_switch_input(xpath, text):
    tmp = driver.find_element_by_xpath(xpath)
    tmp.clear()
    tmp.send_keys(text)

@retry(tries=3, delay=1)
def try_dclick_element(xpath):
    dclick = driver.find_element_by_xpath(xpath)
    ActionChains(driver).double_click(dclick).perform()

options = EdgeOptions()
options.use_chromium = True
options.add_experimental_option('excludeSwitches',['enable-automation'])  # 开启开发者模式
options.add_argument('--disable-blink-features=AutomationControlled')  # 禁用启用Blink运行时的功能
options.binary_location = r'C:\Program Files (x86)\Microsoft\EdgeCore\113.0.1774.50\msedge.exe'
url = 'https://www.baidu.com/'

driver = Edge(options=options, executable_path='./msedgedriver.exe')
driver.get(url)
posted @ 2023-05-22 18:55  wstong  阅读(528)  评论(0编辑  收藏  举报