MENU

Selenium 笔记

May 28, 2022 • 阅读: 1391 • 笔记&折腾

近期开发项目使用了 selenium 工具,此篇为 selenium 开发笔记。

打开指定页面:

# 本地浏览器路径
self.option.binary_location = "C:\\Users\\jxxcl\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"
# 浏览器参数
self.option.add_argument("--disable-web-security")
usr_data_dir = "F:\\xxxx\\xx"
self.option.add_argument(f"--user-data-dir=" + usr_data_dir)
# 驱动
s = Service(r"F:\\xx\\chromedriver_win32\\chromedriver.exe")
# 加载扩展插件
self.option.add_extension("shadow-root.crx")
self.driver = webdriver.Chrome(service=s, options=self.option)
# 设置窗口大小
self.driver.set_window_size(500,300)
self.driver.get("http://xxx")

执行 js 代码:

js = "return gameInst.gameState"
gameState = self.driver.execute_script(js)

js 注入:

js_file = open("./xx/xx.js", encoding='utf-8')
code_lines = js_file.readlines()
js_file.close()
code = "".join(code_lines)
# print(code)
code = "var s= document.createElement('script');"  \
        "s.type='text/javascript';" \
        "s.src='./dom-to-image.js';" \
        "document.body.appendChild(s);"
self.driver.execute_script(code)

根据 XPATH 获取对象

enter_dom = self.driver.find_element(By.XPATH, '//*[@class="class-name"]')

鼠标移动到目标位置:

enter_dom = self.driver.find_element(By.XPATH, '//*[@class="class-name"]')
ActionChains(self.driver).move_to_element(enter_dom).perform()

鼠标点击对象 && 点击当前位置:

enter_dom = self.driver.find_element(By.XPATH, '//*[@class="class-name"]')
ActionChains(self.driver).click(enter_dom).perform()
ActionChains(self.driver).click().perform()

移动到 dom 对象偏移位置点击:

ActionChains(self.driver).move_to_element_with_offset(to_element=search_buttom, xoffset=-0, yoffset=60).click().perform()

输入按键时间:

ActionChains(self.driver).key_down("k").perform()
# 按键时长 0.2s
time.sleep(0.2)
ActionChains(self.driver).key_up("k").perform()
# 同时按键
ActionChains(self.driver).key_down("j").key_down("d").perform()
time.sleep(0.2)
ActionChains(self.driver).key_up("j").key_up("d").perform()
Leave a Comment