Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果没有按钮,如何避免Selenium click函数出错_Python_Selenium - Fatal编程技术网

Python 如果没有按钮,如何避免Selenium click函数出错

Python 如果没有按钮,如何避免Selenium click函数出错,python,selenium,Python,Selenium,我使用此代码单击selenium页面上的按钮: document.getElementsByClassName('pv-profile-section__text-truncate-toggle')[0].click() 有些页面有此按钮,有些页面没有。此按钮不存在的页面上出现错误。如何防止发生此错误?例如,检查此按钮是否在页面上的条件。您可以使用NoTouchElementException执行此操作,或者检查按类名称查找元素返回的列表是否为空: selenium.common.Except

我使用此代码单击selenium页面上的按钮:

document.getElementsByClassName('pv-profile-section__text-truncate-toggle')[0].click()

有些页面有此按钮,有些页面没有。此按钮不存在的页面上出现错误。如何防止发生此错误?例如,检查此按钮是否在页面上的条件。

您可以使用
NoTouchElementException
执行此操作,或者检查
按类名称查找元素返回的列表是否为空:

selenium.common.Exception中的
导入NoTouchElementException
def单击(如果存在)(类别名称:str):
尝试:
驱动程序。通过类名称(类名称)查找元素。单击()
除无任何例外:
打印(f'{class_name}元素不存在')
如果存在,请单击(“SomeRandomClass”)
#SomeRandomClass元素不存在
def如果存在(类别名称:str),请单击:
找到的元素=驱动程序。按类名称(类名称)查找元素
如果找到以下元素:
找到\u元素[0]。单击()
其他:
打印(f'{class_name}元素不存在')
如果存在,请单击(“SomeRandomClass”)
#SomeRandomClass元素不存在

将其置于try块下:

try:
    document.getElementsByClassName('pv-profile-section__text-truncate-toggle')[0].click()
except Exception as e:
    error = e