I have below similar codes. The only difference is the browser I choose. I want to combine the duplicated codes into a function.
driver = webdriver.Chrome()
driver.get('http://www.google.ca')
driver.quit()
driver2 = webdriver.Firefox()
driver2.get('http://www.google.com')
time.sleep(2)
driver2.quit()
I wrote the below function but seems cannot pass the browser_name as part of the command. Any solution for this?
def go_to_baidu(browser_name):
driver = webdriver.browser_name()
driver.get('http://www.baidu.com')
time.sleep(2)
driver.quit()
Instead of passing a value like "Chrome" or "Firefox" to your function, pass webdriver.Chrome or webdriver.Firefox() (without the quotes) instead. The, change the first line of the function like so:
def go_to_baidu(browser_name):
driver = browser_name()
driver.get('http://www.baidu.com')
time.sleep(2)
driver.quit()
You then run it like this:
go_to_baidu(webdriver.Chrome)
for example.
Functions are objects in Python, and can be passed to other functions just as easily as strings, lists, dicts, etc. can.
I have a bit of code that works to automatically log someone into their outlook email in the chrome browser. The user would have to have their email and password inputted into the code for it to work. It works fine until I try to define the body of the code to make it cleaner and to allow for more code to be written underneath without it messing with the function.
from selenium import webdriver
import time
def outlook():
driver = webdriver.Chrome()
x = 'https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=13&ct=1592499273&rver=7.0.6737.0&wp=MBI_SSL&wreply=https%3a%2f%2foutlook.live.com%2fmail%2f0%2finbox%3fRpsCsrfState%3d8a0340e9-f9ec-d8ca-1b7d-c36e5fc0520f%26wa%3dwsignin1.0%26nlp%3d1&id=292841&aadredir=1&CBCXT=out&lw=1&fl=dob%2cflname%2cwld&cobrandid=90015'
driver.get(x)
loginBox = driver.find_element_by_xpath('//*[#id="i0116"]')
loginBox.send_keys('email')
loginButton = driver.find_element_by_xpath('//*[#id="idSIButton9"]')
loginButton.click()
passBox = driver.find_element_by_xpath('//*[#id="i0118"]')
passBox.send_keys('password')
time.sleep(2)
passButton = driver.find_element_by_xpath('//*[#id="idSIButton9"]')
passButton.click()
outlook()
The time.sleep function is because the button click doesn't register when the code runs too fast.
The issue is, the above code with the defined function works normally but closes the chrome window it creates after logging in. If I remove the 'outlook()' and the 'def outlook():' it works fine without closing the chrome window.
I am wondering why that is and if there is a workaround.
Try pulling the webdriver instantiation out. I think it's getting garbage collected- that's the only thing that makes much sense.
edit: Also, driver.get(x) should be indented, I'm pretty sure. Also also, you may run into problems down the line with the driver getting stale. I would set things up as:
with webdriver.Chrome() as driver:
outlook()
(And remove the original driver=webdriver.Chrome() )
from selenium import webdriver
import time
driver = webdriver.Chrome()
def outlook():
x = 'https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=13&ct=1592499273&rver=7.0.6737.0&wp=MBI_SSL&wreply=https%3a%2f%2foutlook.live.com%2fmail%2f0%2finbox%3fRpsCsrfState%3d8a0340e9-f9ec-d8ca-1b7d-c36e5fc0520f%26wa%3dwsignin1.0%26nlp%3d1&id=292841&aadredir=1&CBCXT=out&lw=1&fl=dob%2cflname%2cwld&cobrandid=90015'
driver.get(x)
loginBox = driver.find_element_by_xpath('//*[#id="i0116"]')
loginBox.send_keys('email')
loginButton = driver.find_element_by_xpath('//*[#id="idSIButton9"]')
loginButton.click()
passBox = driver.find_element_by_xpath('//*[#id="i0118"]')
passBox.send_keys('password')
time.sleep(2)
passButton = driver.find_element_by_xpath('//*[#id="idSIButton9"]')
passButton.click()
outlook()
In first file , there is a below code.
I want to use the driver instance of first file in second file , I am able to call it but getting an exception Nosuchelementexception
Basically i want the same browser session in both files , note that import statements are provided properly to use those.
class Init():
driver = webdriver.Chrome(
executable_path="C:\Program Files (x86)\Python36-32\selenium\webdriver\chromedriver_win32\chromedriver.exe")
def take_screenshot(self):
Init.driver.get_screenshot_as_png("Testcase.png")
def browser_launch(self):
Init.driver.set_page_load_timeout(20)
Init.driver.get("http://url/")
Init.driver.maximize_window()
def user_comes_in(self):
Init.driver.find_element_by_id("username").send_keys("admin")
Init.driver.find_element_by_name("password").send_keys("admin")
Init.driver.find_element_by_class_name("Button").click()
Init.driver.set_page_load_timeout(20)
In second file , here is the code
initiate = Init()
class Two(unittest.TestCase):
initiate.browser_launch()
def test_user_logs(self):
initiate.user_comes_in()
print("test case one")
def test_user_create(self):
initiate.user_creation()
print("Test case two")
if you can keep the browser open, you can do it like this:
init.py:
def setDriver():
driver = webdriver.Firefox()
driver.maximize_window()
driver = setDriver()
1.py:
from init.py import driver
driver.get('xxxx')
2.py:
from init.py import driver
driver.get('yyyy')
they will use same driver and same browser.
but if you close the driver in any of the case file, others can't use it again. so it only available in cases don't need to close browser.
I have a function that handles logging into a website. I then return the webdriver instance so that I can pass it into another fucnction that actually handles getting the information that I need.
For some reason I have been unable to call my second function using the returned driver instance.
Was wondering if anyone had any insight into how I can pass a webdriver instance to another function? Thanks.
how I can pass a webdriver instance to another function?
You would return the instance from the first function and call the second function with it.
In the example below, I define 2 functions. A webdriver is instantiaterd inside func1, which returns the instance. Then I call func2, which takes a driver instance as an argument.
from selenium import webdriver
def func1():
driver = webdriver.Chrome()
driver.get('https://example.com')
return driver
def func2(driver):
return driver.title
if __name__ == '__main__':
driver = func1()
title = func2(driver)
print(title)
driver.quit()
This code will launch a browser (Chrome), navigate to a site (https://example.com), print the page title ("Example Domain"), and then quit the browser.
Alternatively, extending Corey Goldberg's answer. It is perfectly fine to simply pass a reference of the driver to all functions that use it.
from selenium import webdriver
def func1(driver):
driver.get('https://example.com')
def func2(driver):
return driver.title
if __name__ == '__main__':
driver = webdriver.Chrome()
func1(driver)
title = func2(driver)
print(title)
driver.quit()
I am on Mac OS X using selenium with python 3.6.3.
This code runs fine, opens google chrome and chrome stays open.:
chrome_options = Options()
chrome_options.binary_location="../Google Chrome"
chrome_options.add_argument("disable-infobars");
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("http://www.google.com/")
But with the code wrapped inside a function, the browser terminates immediately after opening the page:
def launchBrowser():
chrome_options = Options()
chrome_options.binary_location="../Google Chrome"
chrome_options.add_argument("disable-infobars");
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("http://www.google.com/")
launchBrowser()
I want to use the same code inside a function while keeping the browser open.
Just simply add:
while(True):
pass
To the end of your function. It will be like this:
def launchBrowser():
chrome_options = Options()
chrome_options.binary_location="../Google Chrome"
chrome_options.add_argument("disable-infobars");
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("http://www.google.com/")
while(True):
pass
launchBrowser()
My guess is that the driver gets garbage collected, in C++ the objects inside a function (or class) get destroyed when out of context. Python doesn´t work quite the same way but its a garbage collected language. Objects will be collected once they are no longer referenced.
To solve your problem you could pass the object reference as an argument, or return it.
def launchBrowser():
chrome_options = Options()
chrome_options.binary_location="../Google Chrome"
chrome_options.add_argument("start-maximized");
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("http://www.google.com/")
return driver
driver = launchBrowser()
To make the borwser stay open I am doing this:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def browser_function():
driver_path = "path/to/chromedriver"
chr_options = Options()
chr_options.add_experimental_option("detach", True)
chr_driver = webdriver.Chrome(driver_path, options=chr_options)
chr_driver.get("https://target_website.com")
The browser is automatically disposed once the variable of the driver is out of scope.
So, to avoid quitting the browser, you need to set the instance of the driver on a global variable:
Dim driver As New ChromeDriver
Private Sub Use_Chrome()
driver.Get "https://www.google.com"
' driver.Quit
End Sub
This is somewhat old, but the answers on here didn't solve the issue. A little googling got me here
http://chromedriver.chromium.org/getting-started
The test code here uses sleep to keep the browser open. I'm not sure if there are better options, so I will update this as I learn.
import time
from selenium import webdriver
driver = webdriver.Chrome('/path/to/chromedriver') # Optional argument, if not specified will search path.
driver.get('http://www.google.com/xhtml');
time.sleep(5) # Let the user actually see something!
search_box = driver.find_element_by_name('q')
search_box.send_keys('ChromeDriver')
search_box.submit()
time.sleep(5) # Let the user actually see something!
driver.quit()
My solution is to define the driver in the init function first, then it won't close up the browser even the actional
To whom has the same issue, just set the driver to global, simple as following:
global driver
driver.get("http://www.google.com/")
This resolved the problem on my side, hope this could be helpful
Adding experimental options detach true works here:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
As per the code block you shared there can be 3 possible solutions as follows :
In the binary_location you have to change the .. to . (. denotes Project Workspace)
In the binary_location you have to change the .. to /myspace/chrome (Absolute Chrome Binary)
While initiating the driver, add the switch executable_path :
driver = webdriver.Chrome(chrome_options=options, executable_path=r'/your_path/chromedriver')
def createSession():
**global driver**
driver = webdriver.Chrome(chrome_driver_path)
driver.maximize_window()
driver.get("https://google.com")
return driver
To prevent this from happening, ensure your driver variable is defined outside your function or as a global variable, to prevent it from being garbage collected immediately after the function completes execution.
In the example above, this could mean something like:
driver = webdriver.Chrome(chrome_options=get_options())
def get_options():
chrome_options = Options()
chrome_options.binary_location="../Google Chrome"
chrome_options.add_argument("disable-infobars")
return chrome_options
def launchBrowser():
driver.get("http://www.google.com/")
launchBrowser()
Hi the below solutions worked for me Please have a try these.
Solution 1 : of Google chrome closes automatically after launching using Selenium Web Driver.
Check the Version of the Chrome Browser driver exe file and google chrome version you are having, if the driver is not compatible then selenium-web driver browser terminates just after selenium-web driver opening, try by matching the driver version according to your chrome version
The reason why the browser closes is because the program ends and the driver variable is garbage collected after the last line of code. For the second code in the post, it doesn't matter whether you use it in a function or in global scope. After the last statement is interpreted, the driver variable is garbage collected and the browser terminates from program termination.
Solutions:
Set chrome options
Use the time module
Use an infinite loop at the end of your program to delay program closure
You can simply add:-
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)