Selenium 元素定位方式封装的实际应用

2023-06-14,,

一、定位方式

 二、实际应用

1、项目结构

2、locator_base.py 文件

# -*- coding: utf-8 -*-
from selenium.webdriver.common.by import By # 元素定位方式
def locator(driver, find, type, loc):
global element
find_dict = {"ele": driver.find_element, "eles": driver.find_elements} locator_dict = {
"id": By.ID,
"name": By.NAME,
"class": By.CLASS_NAME,
"tag": By.TAG_NAME,
"link": By.LINK_TEXT,
"partial_link": By.PARTIAL_LINK_TEXT,
"xpath": By.XPATH,
"css": By.CSS_SELECTOR
} if type in [key for key in locator_dict.keys()]:
element = find_dict[find](locator_dict[type], loc)
return element
else:
raise NameError("元素定位方式发生错误!") # send_keys()
def send(driver, find, type, loc, data):
try:
locator(driver, find, type, loc).send_keys(data)
print("【{0}】输入成功".format(data))
except:
print("输入失败") # click()
def click(driver, find, type, loc):
try:
locator(driver, find, type, loc).click()
print("点击成功")
except:
print("点击失败")

3、test_case.py 文件

# -*- coding: utf-8 -*-
from eleFZ.locator_base import locator, send, click
from selenium import webdriver
from time import sleep
import unittest class Test_yyds(unittest.TestCase):
"""测试Demo""" @classmethod
def setUpClass(self):
global driver
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/") def test_a_input(self):
"""用例1"""
send(driver, "ele", "id", "kw", "保你平安")
click(driver, "ele", "id", "su")
sleep(3) @classmethod
def tearDownClass(cls) -> None:
driver.close() if __name__ == '__main__':
unittest.main()

Selenium 元素定位方式封装的实际应用的相关教程结束。

《Selenium 元素定位方式封装的实际应用.doc》

下载本文的Word格式文档,以方便收藏与打印。