python selenium inherit webdriver methods - python

I've been looking for a solution to inherit the methods of the python selenium webdriver class so that I can extend/modify its behaviour. I have not found one that work.
For instance, I want to inherit all the methods of the chrome webdriver but extend the .get() method (i.e. the method to load a url). This is my current approach:
from selenium import webdriver
from selenium.common.exception import TimeoutException
class CustomDriver:
def __init__(self, browser):
if browser.lower() == 'chrome'
self.driver = webdriver.Chrome()
def get_url(self, url):
try:
self.driver.get(url)
except TimeoutException:
self.driver.quit()
This methods works but it does not inherit the general webdriver methods like driver.quit(). In fact, if I do the following:
mydriver = CustomDriver('Chrome')
mydriver.quit()
I get the error: 'Custom driver' object has no attribute quit.
Has any of you any suggestions?
ps: I'm new to python.

quit() is from webdriver methods and you are importing it from selenium module, and you have created a object self.driver for the webdriver.Chrome()
so you can't use webdriver method on created class object that is the reason why you are getting No Attribute Error : 'Custom driver' object has no attribute quit
One way of obtaining inheritance is by declaring respective method inside the class and inherit those methods outside.
Refer this document: https://www.geeksforgeeks.org/web-driver-methods-in-selenium-python/
Below is the code that would work
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
class CustomDriver:
def __init__(self, browser):
if browser.lower() == 'chrome':
self.driver = webdriver.Chrome()
def exit_browser(self):
self.driver.quit()
def get_url(self, url):
try:
self.driver.get(url)
except TimeoutException:
self.driver.quit()
mydriver = CustomDriver('Chrome')
mydriver.get_url("https://www.google.com/")
mydriver.exit_browser()

Related

Selenium webdriver not recognized as webdriver

So I have this test and fixture:
#pytest.fixture()
def init_driver():
return webdriver.Chrome(executable_path=TestParams.CHROME_EXECUTABLE_PATH)
#pytest.mark.usefixtures('init_driver')
def test_1():
driver = init_driver
login(driver)
In this case my driver type is <class 'function'> so I cannot use its function for example get and got this error:
AttributeError: 'function' object has no attribute 'get'
When I change it to this:
#pytest.mark.usefixtures('init_driver')
def test_1():
login(webdriver.Chrome(executable_path=TestParams.CHROME_EXECUTABLE_PATH))
My driver type is <selenium.webdriver.chrome.webdriver.WebDriver (session="4ca3cb8f5bcec7a7498a65bfe5a2ea81")>
And all works fine.
What I am doing wrong ?
I fixed the syntax and changed it so that it runs without your hidden methods and variables such as login() and TestParams:
import pytest
from selenium import webdriver
#pytest.fixture()
def init_driver():
driver = webdriver.Chrome()
yield driver
driver.quit()
def test_1(init_driver):
driver = init_driver
print(type(driver))
Running that prints:
<class 'selenium.webdriver.chrome.webdriver.WebDriver'>

AttributeError: type object 'WebTablePage' has no attribute 'load' in selenium using pytest

I am learning selenium in python with pytest, I am facing this below error. I have searched this error all over the internet and tried all the possible advice, but nothing is working.
I am just trying to load the website, it is opening the browser but failing with this error. I don't know what i am missing, Any lead would be helpful.
FAILED Tests/test_webtable.py::test_webtablepage - AttributeError: type object 'WebTablePage' has no attribute 'load'
Code
Page Object Class(webtablepage.py) under pages folder.
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
class WebTablePage:
#URL
URL = 'https://demoqa.com/webtables'
#Intializers
def __init__(self,browser):
browser = self.browser
def load(self,browser):
self.browser.get(self.URL)
Pytest fixture(conftest.py) under Tests folder.
import pytest
import selenium.webdriver
#pytest.fixture
def browser():
#initialize the chrome instance
driver = selenium.webdriver.Chrome()
#Making the Driver wait for 10 seconds to load elements
driver.implicitly_wait(10)
#Return the webdriver instances for the setup
yield driver
#Quit the webdriver instances for the cleanup
driver.quit()
Test function (test_webtable.py) under Tests folder
from Pages.webtablepage import WebTablePage
def test_webtablepage(browser):
Webtable_page = WebTablePage
# Given the demoa qa Webtables page
Webtable_page.load()
The WebTablePage constructor is called incorrectly. It must be called with the browser argument.
Change this:
def test_webtablepage(browser):
Webtable_page = WebTablePage
To this:
def test_webtablepage(browser):
Webtable_page = WebTablePage(browser)
Change the
Webtable_page = WebTablePage
to
Webtable_page = WebTablePage()

Python class to open and close website using Selenium

Trying to setup Chrome for the open / close a website. Now i can open it, But failed to close it.
Can anyone tell me why? Many thanks!
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class chromeSetup():
def __init__(self):
self.chrome_path = r'C:\XXXXX\chromedriver.exe'
def searchWeb(self, url="https://www.google.com.hk/"):
driver = webdriver.Chrome(self.chrome_path)
driver.get(url)
def close(self):
self.driver.close()
You are not making driver an instance attribute. Change searchWeb method like this:
def searchWeb(self, url="https://www.google.com.hk/"):
self.driver = webdriver.Chrome(self.chrome_path)
self.driver.get(url)

Selenium Python: What are the errors in my code?

i would like to know why this code opens mozilla twice, and why it doesn´t close it when finishes. Furthermore, i don´t understand 100% why login is a class with a function, and not a function directly.
> import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class LoginDetails(object):
def __init__ (self):
self.driver = webdriver.Firefox()
def logindetails(self, username, password):
driver = self.driver
driver.maximize_window()
driver.get("https://miclaro.claro.com.ar/")
driver.implicitly_wait(30)
driver.find_element_by_id("_58_login_movil").send_keys(username)
driver.find_element_by_id("_58_password_movil").send_keys(password)
driver.find_element_by_id("btn-home-login").click()
# Login Success
class TestLogin(unittest.TestCase):
def setUp(self):
self.ld = LoginDetails()
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
def test_sr_Login(self):
self.ld.logindetails("user", "pass")
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
Thank you very much!
This is because you instantiate webdriver twice - once inside the TestCase and once inside the LoginDetails class.
Why the other answer is not entirely correct
The WebDriver should not be controlled by the LoginDetails class in this case. LoginDetails class is very close to a Page Object notation representation and, hence, should be given the driver "from outside". Plus, opening browser in one class and closing it in the other is making the code close to "Spaghetti".
Better solution
Control the webdriver from the TestCase class and "share" with the LoginDetails:
import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class LoginDetails(object):
def __init__ (self, driver):
self.driver = driver
def logindetails(self, username, password):
driver = self.driver
driver.maximize_window()
driver.get("https://miclaro.claro.com.ar/")
driver.implicitly_wait(30)
driver.find_element_by_id("_58_login_movil").send_keys(username)
driver.find_element_by_id("_58_password_movil").send_keys(password)
driver.find_element_by_id("btn-home-login").click()
class TestLogin(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.ld = LoginDetails(self.driver)
def test_sr_Login(self):
self.ld.logindetails("user", "pass")
def tearDown(self):
self.driver.close()
Firefox opens twice
In your test self.ld = LoginDetails() runs the __init__ function of LoginDetails() which in turn runs webdriver.Firefox() then you issue the same in the next line in the test case. That is why Firefox opens twice.
Firefox does not close
For the same reason as above Firefox is not closed. The tearDown of your test case only closes the instance of webdriver.Firefox() defined in the test case itself not the one opened via the __init__ function of the class.
Why LoginDetails is a class
LoginDetails is a class in this case to keep webdriver.Firefox() persistent throughout your code. If it would be a function you would open one Firefox session each time you run the function. Unless you specify webdriver.Firefox() outside the function and then pass it to the function.
Corrected Code
The following code uses the class functionality:
import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class LoginDetails(object):
def __init__ (self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
def logindetails(self, username, password):
self.driver.maximize_window()
self.driver.get("https://miclaro.claro.com.ar/")
self.driver.implicitly_wait(30)
self.driver.find_element_by_id("_58_login_movil").send_keys(username)
self.driver.find_element_by_id("_58_password_movil").send_keys(password)
self.driver.find_element_by_id("btn-home-login").click()
def __del__(self):
''' ADDED based on comment by alecxe '''
self.driver.close()
class TestLogin(unittest.TestCase):
def setUp(self):
self.ld = LoginDetails()
def test_sr_Login(self):
self.ld.logindetails("user", "pass")
def tearDown(self):
# driver is closed by LoginDetails
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()

How to to run unitest and selenium from a django view?

I have a functional test 'y1.py' which I have exported from the selenium IDE. It looks like:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re
class Y1(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.yahoo.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_y1(self):
driver = self.driver
driver.get(self.base_url)
driver.find_element_by_link_text("Weather").click()
driver.save_screenshot('out11.png')
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
I am trying to call this directly from within a python/django function. while investigating this I came across: AttributeError 'module' object has no attribute 'runserver' in django, where Udi states:
Are you trying to run unitest and selenium from a view? You should
consider launching a second process for that.
How can I do this?
You can start django server as new process with subprocess module.

Categories