i'm quite new to python. For a psychology project i wrote a little app to collect posts from forums with beautifulsoup (and requests to get the source code of the webpages). Some forums need a login. So i changed my app to do this task with selenium. But i can't figure out how to use the same driver-instance in different classes which are in different files resp. modules. In my PyCharm-Project I added the following class in a extra module:
from selenium import webdriver
class SetDriver():
def __init__ (self, driver):
self.driver = driver
def setUp():
driver = webdriver.Chrome()
return SetDriver(driver)
But if i want to access the instance from my main file or another module for example with this code:
actualsite = "a forum url"
driver = crawler.SetDriver.setUp()
driver.get(actualsite)
I get this error: AttributeError: 'SetDriver' object has no attribute 'get'
I'm pretty sure that i do have a problem with my understanding of OOP here, but after searching the web for a couple of hours now, i couldn't figure out what i do wrong.
Looking forward for some help =) Thx
In your code, the selenium driver is assigned to the the driver
attribute of the SetDriver() class. So you would have to use that attribute whenever you want to reference the driver:
# This should work
actualsite = "https://www.duckduckgo.com"
driver = crawler.SetDriver.setUp()
driver.driver.get(actualsite)
in the above code, the first driver
is your SetDriver()
instance, which is not the actual selenium driver. The actual selenium driver is in the driver
attribute on that class. You can confirm that by checking the type()
of the variables you have created.
actualsite = "https://www.duckduckgo.com"
driver = crawler.SetDriver.setUp()
# check `driver` type
print(type(driver))
# check `driver.driver` type
print(type(driver.driver))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.