selenium 工具 的基本使用

公司每天要做工作汇报,汇报使用的网页版, 所以又想起 selenium 这个老朋友了。

再次上手,发现很多接口都变了, 怎么说呢, 应该是易用性更强了, 不过还是得重新看看, 我这里是python3。

pip安装得现在最新(20231128)版本(4.15.2), 下面做下操作记录。

引入模块

python 复制代码
# selenium 导入
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
python 复制代码
options =Options()
# 为了防止频繁启动终端,可以端口远程一个的方案
# /opt/google/chrome/chrome --remote-debugging-port=9527
crom_url = '127.0.0.1:9527'
options.add_experimental_option("debuggerAddress", crom_url)

epth = './3ds/chromedriver_linux64/chromedriver'
# 这里不太一样, 加了个ChromeService抽象层, 我认为更加合理
service = webdriver.ChromeService(executable_path=epth)
driver = webdriver.Chrome(service=service, options=options)

等待页面打开

python 复制代码
while True:
    driver.get("网址")
    try:
        WebDriverWait(driver, 60, 0.5).until(EC.presence_of_element_located([By.ID, "workBox"]))
        break
    except:
        continue

新版本的定位器不一样了, 我写了个定位发送内容得功能。

python 复制代码
def send_tkey(loc:list, ctx, clear=True):
    time.sleep(random.random())
    obj = None
    if isinstance(loc[0], list):
        for l in loc:
            if len(l) == 2: l.append(0)
            if obj is None:
                obj = driver.find_elements(*l[:2])[l[2]]
            else:
                obj = obj.find_elements(*l[:2])[l[2]]
    else:
        if len(loc) == 2: loc.append(0)
        obj = driver.find_elements(*loc[:2])[loc[2]]
    if clear:
        obj.clear()
        time.sleep(random.random())
    for e in ctx:
        if isinstance(e, list):
            obj.send_keys(*e)
        else:
            obj.send_keys(e)
        time.sleep(random.random())

使用方法:

python 复制代码
#													 前面是定位器参数,               输入内容
send_tkey([[By.CLASS_NAME,'class1'],[By.TAG_NAME,'input']],'工作内容!',False)

定位器的基本用法

python 复制代码
driver.find_elements(By.CLASS_NAME,'class1')[0].find_element(By.TAG_NAME,'input').send_keys(Keys.ENTER)

driver.find_elements(By.CLASS_NAME,'class1')[0].find_element(By.TAG_NAME,'input').click()

PS: 写这类工具,如果不急, 一定要多加延时控制,有一定的反"反爬机制", 也对服务器有好一点,大家好。


参考(项目做了一段时间,可能没有列完, 感谢大家的分享)

相关推荐
終不似少年遊*2 小时前
【软测】接口测试 - 用postman测试软件登录模块
软件测试·测试工具·json·postman·web·可用性测试
程序员三藏1 天前
Jmeter的三种参数化方式详解
自动化测试·软件测试·python·测试工具·jmeter·职场和发展·测试用例
終不似少年遊*3 天前
【软测】node.js辅助生成测试报告
软件测试·测试工具·node.js·postman·web
测试19983 天前
2025软件测试面试题汇总(接口测试篇)
自动化测试·软件测试·python·测试工具·面试·职场和发展·接口测试
zimoyin3 天前
Java/Kotlin selenium 无头浏览器 [Headless Chrome] 实现长截图 三种方式
java·selenium·kotlin
爱记录的小磊4 天前
java-selenium自动化快速入门
java·selenium·自动化
互联网杂货铺4 天前
如何使用Postman做接口自动化测试
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
nvvas4 天前
Python Selenium固定端口测试chrome浏览器绕过登录验证
chrome·python·selenium
车载测试工程师4 天前
Wireshark 筛选功能详解:语法与示例
网络·tcp/ip·测试工具·wireshark
测试杂货铺5 天前
postman接口测试
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman