如何解决错误AttributeError: 'NoneType' object has no attribute 'click'
?它在CCD_ 2中失败。当我不创建页面对象类时,它工作得很好。。。它点击"你"按钮没有任何错误,但通过使用POM它失败了。url为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没有返回元素,因此None是从except
块返回的,该块没有"click"属性。
由于用例是点击文本为的元素,您有几个事实:
- 您不需要等待主页分别用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