【问题标题】:How to fix AttributeError: 'NoneType' object has no attribute 'click'如何修复 AttributeError:“NoneType”对象没有“点击”属性
【发布时间】:2019-02-02 23:01:05
【问题描述】:

如何解决错误AttributeError: 'NoneType' object has no attribute 'click'?它在self.home.get_you_button().click() 中失败了。当我不创建页面对象类时它工作正常......它点击 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

【问题讨论】:

  • 那么你抓到的Exception是什么?
  • 你能发布你的html吗?
  • 在 any Exception 的情况下,您的 get_you_button() 函数显式返回 None。是抓一只吗?如果有,是哪一个?这确实应该包含在问题中。
  • 那么当该函数返回None 并且您尝试在None 上调用.click() 时,您期望会发生什么?那确实会提高您遇到的AttributeError。您是否调试了代码以确保这不是正在发生的事情?同样,所有这些信息都应包含在问题中。
  • @AvinavDas 即使没有引发异常,您的get_you_button 方法也不会显式返回任何内容,这意味着它仍会返回None。

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


【解决方案1】:

此错误消息...

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

...暗示 WebDriverWait 没有返回 element 所以 None 是从没有属性的 except 块返回的“点击”。

由于您的用例是单击带有文本的元素作为您有几个事实:

  • 您不需要单独等待 主页加载 和 WebDriverWait。所以你可以删除方法wait_for_home_page_to_load(self)。
  • 而是在您为 url https://huew.co/ 调用 get() 后诱导 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
    
  • 您必须添加以下导入:

    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
    

【讨论】:

    猜你喜欢
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多