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

时间:2019-02-02 23:01:06

标签: python python-3.x selenium selenium-webdriver webdriverwait

如何解决错误AttributeError: 'NoneType' object has no attribute 'click'?它在self.home.get_you_button().click()中失败。当我不创建Page Object Class时,它工作正常。它单击“ You”按钮,没有任何错误,但是使用POM失败。网址为https://huew.co/

代码试用:

from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

class HomePage():

    def __init__(self,driver):
        self.driver = driver

    def wait_for_home_page_to_load(self):
        wait =WebDriverWait(self.driver,30)
        wait.until(expected_conditions.visibility_of(self.driver.find_element_by_tag_name('html')))

    def get_you_button(self):

        try:
            element = self.driver.find_element_by_xpath("//div[@class='desktop-public-header']/a[@ng-controller='UserNavigationInteractionCtrl'][6]")

        except:
            return None

1 个答案:

答案 0 :(得分:0)

此错误消息...

AttributeError: 'NoneType' object has no attribute 'click'

...表示 WebDriverWait 没有返回元素,因此从except块中返回的 None 没有属性为“点击”。

用例中,点击带有以下文字的元素

  • 您不需要分别用 WebDriverWait 等待主页加载。因此,您可以删除方法wait_for_home_page_to_load(self)
  • 相反,一旦您为网址get()调用https://huew.co/就会诱导所需元素的 WebDriverWait ,即文本为 You 的元素为< em>可点击。
  • 最好捕获实际的异常 TimeoutException
  • 不确定您的用例,但没有意义返回,而是打印相关文本和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
    
  • 您必须添加以下导入:

    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