擅长:python、mysql、java
<h2>编辑:</h2>
<p>我忘记了<code>find_elements_by_xpath()</code>返回一个空的或非空的列表,但是这个解决方案对于各种<code>find_element_by_*</code>函数是很好的。在</p>
<hr/>
<p>您可以使用<a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions" rel="nofollow noreferrer">try-except-else</a>语句。例如</p>
<pre><code>try:
searchCount = browser.find_element_by_xpath("//a[class='nclk']")
searchCountCheck = len(searchCount)
except NoSuchElementException:
print("No element found. Breaking...")
except:
print("Generic error message.")
else:
# Do stuff with searchCount / searchCountCheck / etc.
</code></pre>
<p>只有在<code>try</code>部分没有抛出错误时,<code>else</code>部分才被输入。在</p>