I'm trying to use ChromeDriver
within with block to make the code look better and get rid of using driver.quit()
command in the end. However, It doesn't seem to work. As soon as the browser opens, it throws the following error. Perhaps, I doing something wrong. Ain't there any way to do so? Thanks in advance.
This is what I've tried:
from selenium import webdriver
with webdriver.Chrome() as wd:
res = wd.get('https://stackoverflow.com/questions/')
print(res.page_source)
#Another failure attempt with the same error
with webdriver.Chrome() as wd:
wd.get('https://stackoverflow.com/questions/')
print(wd.page_source)
This is the error I'm having:
with webdriver.Chrome() as wd:
AttributeError: __exit__
Now it's added to selenium (SeleniumHQ/selenium#5919) so you can simply use the original approach from your question:
from selenium import webdriver
with webdriver.Chrome() as wd:
res = wd.get('https://stackoverflow.com/questions/')
print(res.page_source)
Try below solution and let me know in case it's not what you want:
from selenium import webdriver
class WebDriver:
def __init__(self, driver):
self.driver = driver
def __enter__(self):
return self.driver
def __exit__(self, exc_type, exc_val, exc_tb):
self.driver.quit()
with WebDriver(webdriver.Chrome()) as wd:
wd.get('https://stackoverflow.com/questions/')
print(wd.page_source)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With