仅当存在Web元素时,如何单击按钮?

时间:2019-01-30 07:54:22

标签: python-3.x selenium

我需要对脚本进行编码,以使其仅在可用/存在时才单击Web元素,因为它可能每次都不会出现在Web门户上。我希望单击它(如果存在),而如果不存在则不执行任何操作。

我只能设法进行编码,以便脚本将单击Web元素。但是,当不存在web元素时,脚本将遇到错误并停止运行。

driver.find_element_by_id("smb_server").click()
alert=driver.switch_to_alert()
alert.accept()

我需要编写一种编码方式,使其仅在存在时单击Web元素

2 个答案:

答案 0 :(得分:2)

如果元素也不存在,下面也不会引发任何错误,请尝试以下代码:

elements  = driver.find_elements_by_id('smb_server')
if len(elements) > 0:
    elements[0].click()
    alert=driver.switch_to_alert()
    alert.accept()
else:
    print('Do nothing...')

如果该元素存在,那么我们将获得大于零的长度,因此我们将单击否则将不执行任何操作。或者,您可以执行以下操作:

try:
    driver.find_element_by_id("smb_server").click()
    alert=driver.switch_to_alert()
    alert.accept()
except:
    print("Do Nothing")

答案 1 :(得分:0)

仅检查其存在如何?做

from selenium.common.exceptions import NoSuchElementException

def find_element_if_present(id):
    try:
        return driver.find_element_by_id(id)
    except NoSuchElementException:
        return None

element = find_element_if_present(id="smb_server")
if element is not None:
    element.click()
    alert = driver.switch_to_alert()
    alert.accept()
else:
    #...


但是,鉴于该元素在完全呈现之前可能需要花费一些时间,您可能需要稍微wait。参见

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

WebDriverWait(
    driver, timeout=3, poll_frequency=.5
).until(
    EC.visibility_of_element_located((By.ID, "smb_server"))
#or EC.presence_of_element_located((By.ID, "smb_server"))
)

还有其他expected_conditions,例如

title_is
title_contains
presence_of_element_located
visibility_of_element_located
visibility_of
presence_of_all_elements_located
text_to_be_present_in_element
text_to_be_present_in_element_value
frame_to_be_available_and_switch_to_it
invisibility_of_element_located
element_to_be_clickable
staleness_of
element_to_be_selected
element_located_to_be_selected
element_selection_state_to_be
element_located_selection_state_to_be
alert_is_present

来源:https://selenium-python.readthedocs.io/waits.html