我是Python新手,所以经过多次尝试,我决定第一次寻求帮助。
我收到以下错误:
AttributeError: 'WebDriver' object has no attribute 'driver'
你能帮我理解这是什么意思以及为什么会发生吗?
我的代码如下。
文件:ChromeBrowser.py
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("disable-infobars")
driver = webdriver.Chrome(options=options, service=Service(ChromeDriverManager().install()))
def init_driver(url):
driver.get(url)
return driver
文件:helpers.py
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class LogIn:
def __init__(self, driver):
self.driver = driver
def choose_method(self,method,locator):
self.method = method
self.locator = locator
WebDriverWait(self.driver,10).until(EC.visibility_of_element_located((self.method,self.locator))).click()
文件:run.py
from Log_In.ChromeBrowser import *
from Log_In.constants import Constants as C
from Log_In.helpers import LogIn
from selenium.webdriver.common.by import By
def run():
browser = init_driver(C.url)
LogIn.choose_method(browser, By.CSS_SELECTOR, '#credentialSignin')
if __name__ == '__main__':
run()
我尝试首先运行 run.py 文件。浏览器已使用正确的网站打开(URL 从
constants.py
文件传递),据我了解,Chrome 实例存储在 browser 对象中。然后使用类 LogIn 和方法 choose_method 我想等待网站的正确元素以及何时可以明显地单击它。
问题可能出在 run.py 文件中。 尝试以下操作:
def run():
browser = init_driver(C.url)
# Create an instance of the LogIn class
login_page = LogIn(browser)
# Call the choose_method method on the instance
login_page.choose_method(By.CSS_SELECTOR, '#credentialSignin')
在您的代码中,您尝试调用类上的 choice_method,这并不完全是它的工作原理。 通常,每当您处理类(例如 Dog_Class)时,您都希望为代码中的每只狗创建一个实例。 dog_1 = Dog_Class()、dog_2 = Dog_Class() 等。此时,您只需执行 dog_1.a_method(args) 即可利用每个 Dog_Class 方法和属性。 希望这有帮助