[英]Python selenium driver instance not defined even though instance is returned by method
I am using Selenium in Python 3.7 with Firefox and the gecko driver.我在 Python 3.7 中使用 Selenium 和 Firefox 和 gecko 驱动程序。 I have a method that calls another method to log into a site.我有一种方法可以调用另一种方法来登录站点。 The log in method creates a driver instance, logs in, and returns the driver instance.登录方法创建一个驱动程序实例,登录并返回驱动程序实例。 The original method is then supposed to proceed but I get an error 'driver' is not defined
.然后应该继续使用原始方法,但我收到错误'driver' is not defined
。 I've done some research and near as I can tell, I'm doing everything right.我做了一些研究,据我所知,我做的一切都是正确的。 Here is what I have, I just cut out a lot of the page navigating:这是我所拥有的,我只是剪掉了很多页面导航:
def navigate():
login()
driver.get("http://www.example.com")
def login():
driver = webdriver.Firefox(executable_path="./geckodriver.exe")
...(login code here)
return driver
When calling the navigate method, Firefox opens and logs in fine but when going to the example URL it says driver is not defined.调用导航方法时,Firefox 会打开并正常登录,但在转到示例 URL 时,它说驱动程序未定义。 I can't figure out what I am doing wrong.我无法弄清楚我做错了什么。 I'm not sure why it says driver is not defined.我不确定为什么它说驱动程序未定义。
EDIT: I just found out if I make driver global it will work but why doesn't it work by returning it?编辑:我刚刚发现如果我将驱动程序设为全局,它会起作用,但为什么通过返回它不起作用? I don't necessarily need it to be global.我不一定需要它是全球性的。
As you didn't post your code, it can only ever be a guess... however, it sounds like you're simply not assigning the returned object to your driver
variable.由于您没有发布代码,因此只能猜测……但是,听起来您只是没有将返回的对象分配给driver
变量。
That issue is present in your incomplete code that you gave, it should look like:该问题存在于您提供的不完整代码中,它应该如下所示:
def navigate():
driver = login()
driver.get("http://www.example.com")
def login():
driver = webdriver.Firefox(executable_path="./geckodriver.exe")
...(login code here)
return driver
The change here is that now driver
is assigned the value of the returned login()
object.这里的变化是现在driver
被分配了返回的login()
对象的值。 It works when making driver
a global because then the navigate()
function has visibility of the driver
object from login()
.它在将driver
为全局时起作用,因为之后navigate()
函数可以从login()
看到driver
对象。
Odd that you didn't get/notice a not defined error.奇怪的是您没有收到/注意到未定义的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.