如何修复 AttributeError:“NoneType”对象没有属性“click”

Avi*_*Das 2 python selenium python-3.x selenium-webdriver webdriverwait

如何解决错误AttributeError: \'NoneType\' object has no attribute \'click\'?它的失败在于self.home.get_you_button().click(). 当我没有创建页面对象类时,它\xe2\x80\x99s 工作正常...它单击“You”按钮,没有任何错误,但通过使用 POM,它\xe2\x80\x99s 失败。网址是https://huew.co/

\n\n

代码试验:

\n\n
from selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nclass HomePage():\n\n    def __init__(self,driver):\n        self.driver = driver\n\n    def wait_for_home_page_to_load(self):\n        wait =WebDriverWait(self.driver,30)\n        wait.until(expected_conditions.visibility_of(self.driver.find_element_by_tag_name(\'html\')))\n\n    def get_you_button(self):\n\n        try:\n            element = self.driver.find_element_by_xpath("//div[@class=\'desktop-public-header\']/a[@ng-controller=\'UserNavigationInteractionCtrl\'][6]")\n\n        except:\n            return None\n
Run Code Online (Sandbox Code Playgroud)\n

Deb*_*anB 5

这个错误信息...

AttributeError: 'NoneType' object has no attribute 'click'
Run Code Online (Sandbox Code Playgroud)

...意味着WebDriverWait没有返回任何元素,因此没有从没有“click”属性的块返回任何元素。except

由于您的是单击带有文本的元素,因此有几个事实:

  • 您不需要单独使用WebDriverWait等待主页加载。所以你可以删除该方法。wait_for_home_page_to_load(self)
  • 相反,一旦您调用get()url,https://huew.co/就会诱导WebDriverWait获取所需的元素,即文本为You点击的元素。
  • 最好捕获实际的异常TimeoutException
  • 不确定您的用例,但没有必要返回None而是打印相关文本和break
  • 您可以使用以下解决方案:

    self.driver = driver
    try:
        return (WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class= 'desktop-menu-container ng-scope' and @href='/profile/']"))))
        print("YOU link found and returned")
    except TimeoutException:
        print("YOU link not found ... breaking out")
        break
    
    Run Code Online (Sandbox Code Playgroud)
  • 您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException
    
    Run Code Online (Sandbox Code Playgroud)