You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Selenium常用导入语句复用的优化方法问询

批量复用Selenium导入语句的简便方法

这里给你几种适配场景的简便复用方式:

方法1:批量导入指定内容(最省心)

先给fileA添加导出声明,明确对外暴露的内容,避免导入冗余:

# fileA.py
from selenium import webdriver
from selenium.webdriver.common.by import By

__all__ = ["webdriver", "By"]  # 指定允许被批量导入的对象

然后在fileB里直接批量导入,不用加任何前缀就能使用:

# fileB.py
from import_selenium_import_funcs.fileA import *

# 直接调用webdriver
driver = webdriver.Firefox()
# 直接使用By定位元素
driver.find_element(By.ID, "some-id")

这种方式一次导入就能用所有预定义的Selenium工具,完全省去重复写导入语句的麻烦,非常适合新手场景。

方法2:给模块起短别名(兼顾简洁和避免冲突)

如果你担心*导入会引发变量重名,可以给fileA起个简短别名:

# fileB.py
from import_selenium_import_funcs import fileA as sel

driver = sel.webdriver.Firefox()
element = driver.find_element(sel.By.ID, "some-id")

短别名sel比原模块名好写很多,同时能清晰区分来源,避免冲突。

方法3:扩展导入集合(按需更新)

后续如果要添加更多Selenium工具(比如WebDriverWait),只需在fileA里补充导入,fileB不用修改导入语句就能直接用:

# fileA.py 更新后
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

__all__ = ["webdriver", "By", "WebDriverWait"]
# fileB.py 无需修改导入,直接用新工具
wait = WebDriverWait(driver, 10)

内容的提问来源于stack exchange,提问作者Dri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 09:53:19