Issue
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.
Solution
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()
Answered By - LearnerLaksh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.