使用Seleniumbase无法上传文件,脚本运行无反应求助排查
问题原因及解决方案
核心问题分析
测试方法未被触发执行
你定义了继承自BaseCase的测试类,但没有添加测试运行的入口代码。SeleniumBase需要通过特定方式触发测试逻辑,否则test_visible_upload方法根本不会执行——这就是脚本显示Process finished with exit code 0但没有任何页面操作的根本原因。错误的Driver初始化方式
SeleniumBase的BaseCase类会自动管理Driver的创建、生命周期和销毁,你手动调用get_driver("chrome")并赋值给self.driver,会破坏框架的内置机制,导致后续页面操作(如open/type/click)无法正常工作,这也是你无法获取页面标题的直接原因之一。缺少可靠的页面等待逻辑
页面跳转(如登录后)需要时间完成渲染,直接注释掉sleep又未使用框架自带的显式等待方法,会导致元素未加载完成就执行操作,即使元素路径正确也会失效。代码语法错误
代码中print(title)后和self.choose_file前的反引号(`)属于多余字符,会触发语法错误,需要删除。
修正后的完整代码
from seleniumbase import BaseCase import logging import os logging.basicConfig(level=logging.INFO, filename="py_log.log", format='%(asctime)s - %(levelname)s - %(message)s') logging.info('The script is starting to run') class MyTestClass(BaseCase): def test_visible_upload(self): file_path = os.path.abspath("file.xlsx") self.open("https://site/") # 等待页面初始加载完成 self.wait_for_page_load() self.type('#ke-form-field-input-0', 'login') self.type('#ke-form-field-input-1', 'password') # 等待登录按钮可点击后再执行点击 login_btn_selector = 'body > kn-app > kn-auth > kn-auth-sign-in > kn-auth-sign-in-form > form > button' self.wait_for_element_clickable(login_btn_selector) self.click(login_btn_selector) # 登录后等待页面跳转完成,再获取标题 self.wait_for_page_load() title = self.get_title() print(title) logging.info(f"Page title after login: {title}") # 等待上传元素出现后再执行文件选择 upload_selector = '#kpp-app > div.body > div > div.content-side > div > div.content > div > div.cs-section > div > div > label > div > input[type=file]' self.wait_for_element_present(upload_selector) self.choose_file(upload_selector, file_path) logging.info("File upload initiated") # 添加测试运行入口 if __name__ == "__main__": MyTestClass.main()
运行说明
- 确保安装最新版本的SeleniumBase:
pip install -U seleniumbase - 直接运行脚本即可,或用pytest执行(推荐,支持更多测试特性):
pytest your_script_name.py -v
内容的提问来源于stack exchange,提问作者Alfred Tagirov
相关产品推荐
相关产品推荐

