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

时间:2013-10-08 18:00:02

标签: python selenium-webdriver

我绝不是硒专家,所以我来谦卑地寻求帮助。在执行下面的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?任何帮助表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:3)

您可以尝试以下方式:

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"