Selenium中的异常处理,如何遍历一堆元素定位器直到一个工作

问题描述

我要单击的按钮的ID正在动态更改。例如,id将为id = Button7,那么下次我运行代码时,其ID为Button19。我注意到它遍历了一组ID,但没有特定顺序。

我想遍历所有可能的解决方案,直到其中一个可行。想做与此逻辑类似的事情。

    try:
        source8 = driver.find_element_by_xpath('//*[@id="xl_dijit-bootstrap_Button_99"]')
        ActionChains(driver).click(source8).perform()
    except Exception as e:
        source8 = driver.find_element_by_xpath('//*[@id="xl_dijit-bootstrap_Button_7"]')
        ActionChains(driver).click(source8).perform()
    except Exception as e:
        source8 = driver.find_element_by_xpath('//*[@id="xl_dijit-bootstrap_Button_27"]')
        ActionChains(driver).click(source8).perform()

解决方法

您可以使用包含XPath轴先检测ID,然后再执行必要的操作。

elementId = driver.find_element_by_xpath("//input[contains(@id,'xl_dijit-bootstrap_Button_')]")

elementId.click()

否则,如果您希望对特定ID进行其他操作,然后检索其属性,并使用此属性('idTextAttribute'),可以实现切换用例。

idTextAttribute = elementId.get_attribute("id")

    def SwitchToId(idTextAttribute):
        switcher = {
            "xl_dijit-bootstrap_Button_99": Do Something,like click Or sendKeys,"xl_dijit-bootstrap_Button_7": Do Something,"xl_dijit-bootstrap_Button_27": Do Something,}
        return switcher.get(idTextAttribute,"ID not Found")

注意:Python没有像Java这样的切换用例,因此您可以尝试使用switcher或if-elif块。

,

只需遍历xpath:

for xpath in ['//xpath1','//hpath2','//xpath3']:
  try:
    # do something with xpath
    break
  except:
   print(xpath + " failed!")