Selenium Python-如果元素不存在,则执行此操作,els

2024-05-26 07:46:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我决不是硒专家,因此我谦恭地来这里寻求帮助。在执行了下面的python脚本之后,我想如果它在两次打印之间失败了,我可以简单地查看日志并查看最后一次打印的位置。不幸的是,脚本一直运行到最后,并打印所有内容,无论是否成功。以下是我所拥有的:

print("Attempting, map zoom 4x.")
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
print("Zoom in 4x. Successful")

我要做的是:

print("Attempting, map zoom 4x.")
if driver.find_element_by_xpath ...... exists,
then
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   driver.find_element_by_xpath("//*[@class=\"leaflet-control-zoom-in\"]").click()
   print("Zoom in 4x. Successful")
else
   print("Element does not exist, it failed.")

我将如何为python/selenium设置格式?如有任何帮助,我们将不胜感激。谢谢您。


Tags: in脚本mapbydriverelementfindxpath
1条回答
网友
1楼 · 发布于 2024-05-26 07:46:27

你可以试试这样的方法:

print("Attempting, map zoom 4x.")
elem = driver.find_element_by_xpath('/xpath/to/your/element/here')
if elem.is_displayed():
    elem.click()
    print("Zoom in 4x. Successful")
else:
    print "Element is not visible"

相关问题 更多 >