如何解决错误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/