python - 如何修复属性错误: 'NoneType' object has no attribute 'click'

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

如何解决错误AttributeError:'NoneType'对象没有属性'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

最佳答案

此错误消息...

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

...暗示 WebDriverWait 没有返回任何元素,因此从 except block 中返回了 None没有“点击”属性。

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

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

    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
    

关于python - 如何修复属性错误: 'NoneType' object has no attribute 'click' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54498343/

相关文章:

python - 如何在 Python 中找到 Student-t 分布的幂律参数?

python - 为什么 winfo_width() 返回的按钮小部件尺寸大于其实际尺寸?

python - 错误未绑定(bind)方法 get() 必须使用 phantomJs 通过 WebDriver 调用

html - selenium find_elements_by_tag_name ("img") 会捕获 CSS 图像吗?

ruby - cucumber 自动使用标签重新运行失败的场景?

python - __getattr__ 和 __getattribute__ 用于动态生成的类的类/静态属性

python - 使用数据透视表 pandas 后如何摆脱多级索引?

python - 从 Python 发送电子邮件

python - 如何在 python 中使用 dotenv 在本地 .env 文件中设置环境变量?

Python/Pyserial : reading incoming information from port