我是python的新手,注意这段代码在没有放入函数时编写。
from selenium import webdriver
driver = lambda: None
def setup_browser():
# unnecessary code removed
driver = webdriver.Firefox()
return driver
setup_browser()
driver.set_window_size(1000, 700)
driver.get("https://icanhazip.com/")
如上所示,我收到此错误:
`AttributeError: 'function' object has no attribute 'set_window_size'
我的阅读是驱动程序在被调用之前没有被更新。这是为什么?
答案 0 :(得分:2)
问题在于setup_browser()
内部您正在设置名为driver
的局部变量,但您没有修改全局变量driver
。为此,您需要使用global
关键字:
def setup_browser():
global driver
driver = webdriver.Firefox()
return driver
但是,覆盖driver
全局变量并同时返回它是多余的。最好不要将driver
全局定义为空函数,而是直接分配它。如,
from selenium import webdriver
def setup_browser():
driver = webdriver.Firefox()
return driver
driver = setup_browser()
driver.set_window_size(1000, 700)
driver.get("https://icanhazip.com/")