[英]How can I define driver = webdriver.Firefox without automatically opening the browser?
Here's my code in a simplified way:这是我的代码以简化的方式:
from selenium import webdriver
driver = webdriver.Firefox(executable_path=r"F:\geckodriver.exe")
class Acesso():
def __init__(self):
driver.get(link)
def scroll():
# Function
driver.click()
def url():
# driver.get("https://google.com")
Acesso()
Writing it this way makes the browser to open up as soon as I define my driver
variable.以这种方式编写它会使浏览器在我定义driver
变量后立即打开。 Is there any way I can define the webdriver.Firefox()
without automatically opening the browser?有什么方法可以在不自动打开浏览器的情况下定义webdriver.Firefox()
吗? My goal here is that I want to define the driver
variable inside my __init__
function so I can pass an argument to it.我的目标是我想在我的__init__
函数中定义driver
变量,以便我可以向它传递一个参数。 Something like this:像这样的东西:
def __init__(self, agent):
self.agent = agent
driver = webdriver.Firefox(executable_path=r"F:\geckodriver.exe",firefox_profile=agent)
My issue is that writing it this way I can't use the driver
variable in other functions and if I define the variable for each function the browser will open automatically at any function's call.我的问题是这样写我不能在其他函数中使用driver
变量,如果我为每个函数定义变量,浏览器将在任何函数调用时自动打开。 Any solutions?任何解决方案?
Try this: Create the driver variable but initialize it to None.试试这个:创建驱动程序变量,但将其初始化为无。
Then, in each function that uses it, check if it's None and if it is, then set it to Firefox(...) -- if it's not None, assume it's already set to the Firefox browser and proceed that way.然后,在每个使用它的函数中,检查它是否为 None,如果是,则将其设置为 Firefox(...) -- 如果它不是 None,则假设它已设置为 Firefox 浏览器并继续进行。
Then the browser should open the first function and stay open/be reused for the rest.然后浏览器应该打开第一个函数并保持打开状态/其余部分可以重用。
from selenium import webdriver
try:
fireFoxOptions = webdriver.FirefoxOptions()
fireFoxOptions.set_headless()
brower = webdriver.Firefox(firefox_options=fireFoxOptions, executable_path=r"F:\geckodriver.exe")
Found a solution setting the driver
variable as global
.找到了将driver
变量设置为global
的解决方案。 Now I can define inside my function and still use it on other functions.现在我可以在我的函数内部定义并仍然在其他函数上使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.