Skip to main content
 首页 » 编程设计

python之使用 "OR"组合多个 Selenium 等待

2024年12月31日10mfrbuaa

我的 selenium 代码通过等待网站标题更改来检查是否完成了一个完整的子例程,这非常有效。代码如下所示:

waitUntilDone = WebDriverWait(session, 15).until(EC.title_contains(somestring)) 

但是,这有时会失败,因为网站的着陆页会在手动网站访问后发生变化。服务器会记住您离开的地方。这迫使我检查替代条件(网站标题 =“somestring2”)。

这是我到目前为止想出的(据我所知也有效):

    try: 
        waitUntilDone = WebDriverWait(session, 15).until(EC.title_contains(somestring)) # the old condition 
    except: 
        try: 
            waitUntilDone = WebDriverWait(session, 15).until(EC.title_contains(somestring2)) # the new other condition which is also valid 
        except: 
            print "oh crap" # we should never reach this point 

这些条件中的任何一个总是为真。我不知道你是哪一个。

是否有任何方法可以在这些等待中包含“OR”或使 try/except block 看起来更好?

请您参考如下方法:

看起来 selenium 会让您通过创建自己的类来做到这一点。在此处查看文档:http://selenium-python.readthedocs.io/waits.html

这是您的案例的一个简单示例。请注意,关键是在您的类中有一个名为 __call__ 的方法来定义您想要的检查。 Selenium 将每 500 毫秒调用一次该函数,直到它返回 True 或一些非空值。

class title_is_either(object): 
 
  def __init__(self, locator, string1, string2): 
    self.locator = locator 
    self.string1 = string1 
    self.string2 = string2 
 
  def __call__(self, driver): 
    element = driver.find_element(*self.locator)   # Finding the referenced element 
    title = element.text 
    if self.string1 in title or self.string2 in title 
        return element 
    else: 
        return False 
 
# Wait until an element with id='ID-of-title' contains text from one of your two strings 
somestring = "Title 1" 
somestring2 = "Title 2" 
 
wait = WebDriverWait(driver, 10) 
element = wait.until(title_is_either((By.ID, 'ID-of-title'), somestring, somestring2))