Selenium Try Catch Python[拖放文件上传]



我想写一个代码,检查一个网站是否有拖放功能。为了实现这一点,我首先检索网站的所有元素,并尝试通过拖放上传文件。然而,当我得到一个拖放的无效id,我得到一个selenium.common.exceptions.WebDriverException: Message: <unknown>: Element not interactablet异常。我试着用try/catch块来解决它,但它仍然不起作用。

ids = driver.find_elements_by_xpath('//*[@id]')

counter = 0 
for ii in ids:
print(ii,ii.get_attribute('id'))
driver.find_element_by_id(ii.get_attribute('id'))
dropzone = driver.find_element_by_id(ii.get_attribute('id'))
try:
dropzone.drop_files("/temp/pythonSelenium/test.txt")

except ElementNotInteractableException:
continue

您可能捕获了错误的错误。错误信息显示:

selenium.common.exceptions.WebDriverException: Message: <unknown>: Element not interactable

可以看到,错误消息源是WebDriverException而不是ElementNotInteractableException。这有点令人困惑,但如果你想捕获一个错误,你必须寻找源代码。

因此,为了捕获错误,你必须将代码更改为:

try:
dropzone.drop_files("/temp/pythonSelenium/test.txt")
except WebDriverException:
continue

最新更新