Python导入模块调用Selenium驱动报错问题求助
问题原因及解决方案
原因
主程序里定义的driver变量属于主模块的局部作用域,你导入的login函数所在的模块无法直接访问这个变量——Python中不同模块的变量作用域相互独立,没有明确传递的话,跨模块拿不到其他模块的局部变量,所以运行时会抛出driver未定义的错误。
解决方法
推荐方案:将driver作为参数传入login函数
这种方式依赖关系明确,代码耦合度低,是更规范的写法。
修改模块Modules/login.py的代码:
from selenium.webdriver.common.by import By def login(driver): username = "admin" password = "admin" driver.find_element(By.XPATH, '//*[@id="loginModel"]/div/div/div[3]/input[1]').send_keys(username) driver.find_element(By.XPATH, '//*[@id="loginModel"]/div/div/div[3]/input[2]').send_keys(password) driver.find_element(By.XPATH, '//*[@id="loginModel"]/div/div/div[5]/a/div/div').click()
修改主程序代码:
from selenium.webdriver.chrome.service import Service from selenium import webdriver from selenium.webdriver.common.by import By import time from Modules.login import login driver = webdriver.Chrome() driver.get("http://172.16.115.124:8080/econsole") login(driver) # 把driver对象作为参数传给login函数 time.sleep(10)
不推荐方案:使用全局变量
这种方式会让模块和主程序耦合度变高,不利于后续维护,仅作了解:
修改主程序代码:
from selenium.webdriver.chrome.service import Service from selenium import webdriver from selenium.webdriver.common.by import By import time from Modules import login driver = webdriver.Chrome() driver.get("http://172.16.115.124:8080/econsole") login.login() time.sleep(10)
修改模块Modules/login.py的代码:
from selenium.webdriver.common.by import By import __main__ def login(): username = "admin" password = "admin" __main__.driver.find_element(By.XPATH, '//*[@id="loginModel"]/div/div/div[3]/input[1]').send_keys(username) __main__.driver.find_element(By.XPATH, '//*[@id="loginModel"]/div/div/div[3]/input[2]').send_keys(password) __main__.driver.find_element(By.XPATH, '//*[@id="loginModel"]/div/div/div[5]/a/div/div').click()
内容的提问来源于stack exchange,提问作者pawelek4318
相关产品推荐
相关产品推荐

