Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/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 返回';名称错误';而不是';通过';什么时候可以';找不到元素_Python_Selenium_Nameerror_Nosuchelementexception - Fatal编程技术网

Python 返回';名称错误';而不是';通过';什么时候可以';找不到元素

Python 返回';名称错误';而不是';通过';什么时候可以';找不到元素,python,selenium,nameerror,nosuchelementexception,Python,Selenium,Nameerror,Nosuchelementexception,我正在使用Python Selenium。当我尝试这个: try: element = driver.find_element_by_xpath('--path--').text.encode('ascii','ignore') except NoSuchElementException: pass print element 但是,当元素不存在时,显示错误 NameError: name 'element' is not defined ..当它在找不到元素时应该只通过

我正在使用Python Selenium。当我尝试这个:

try:
    element = driver.find_element_by_xpath('--path--').text.encode('ascii','ignore')
except NoSuchElementException:
    pass


print element
但是,当元素不存在时,显示错误

NameError: name 'element' is not defined

..当它在找不到元素时应该只通过
时。

错误是因为您仅在try部分中设置元素。将
'element'
设置在外部
尝试除外或在除外中设置

Ex:

try:
    element = driver.find_element_by_xpath('--path--').text.encode('ascii','ignore')
except NoSuchElementException:
    element = None

当元素不存在时,根据代码块中的
try{}
块引发异常:

element = driver.find_element_by_xpath('--path--').text.encode('ascii','ignore')
在这里变量元素永远不会初始化

异常在
catch{}
块中处理,您只需按如下方式传递它:

except NoSuchElementException:
    pass
因此,当您尝试
print()
变量元素时,请向前移动,如下所示:

print element
您可以看到Python错误如下所示:

NameError: name 'element' is not defined

Python/Selenium/WebDriver/WebBrowser版本信息请?Python 2.7.14 driver=WebDriver.Firefox()*但是,我主要考虑的是
try
,除了我忽略的
规则。所以,只需将
打印元素
放入
try
块我有很多
try
块。需要一起打印*下面的Rakesh解决它。好的。谢谢你,拉凯什。我只是把
None
放在前面。