【问题标题】:Selenium Python - If element does not exist then do this, else [duplicate]Selenium Python - 如果元素不存在,则执行此操作,否则 [重复]
【发布时间】:2013-10-08 18:00:01
【问题描述】:

我绝不是硒专家,因此我谦虚地来到这里寻求帮助。在执行下面的 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 设置格式?任何帮助表示赞赏。谢谢。

【问题讨论】:

    标签: python selenium-webdriver


    【解决方案1】:

    你可以试试这样的:

    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"
    

    【讨论】:

    • 谢谢 qaduderino,我现在就试试这个。将报告结果。
    • 似乎 selenium 挂在 driver.find....等上。因为它找不到开始的元素。我试过直接进入 if 语句。如果 driver.find_element_by_xpath(.....).is_displayed(): 也失败了。
    • print("尝试在任务列表中点击高亮'missionname'。") if self.is_element_present(By.XPATH, "//*[contains(text(), '123') ]"): print("找到元素。单击突出显示。") driver.find_element_by_xpath("//*[contains(text(), '123')]").click() else: self.fail("Click-高亮失败。找不到元素?")
    • 抱歉格式化。无法弄清楚code
    • 嗯,我从未尝试过 is_element_present。我得去看看
    猜你喜欢
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2014-11-04
    相关资源
    最近更新 更多