使用“OR”组合多个Selenium等待?

2024-04-29 14:02:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我的selenium代码通过等待站点标题的更改来检查要完成的子例程,该子例程运行得非常好。代码如下:

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

然而,这有时会失败,因为网站的登录页面在手动访问网站后发生了变化。服务器会记住你离开的地方。这迫使我检查另一个条件(website title=“somestring2”)。在

以下是我到目前为止得出的结论(据我所知,也是有效的):

^{pr2}$

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

有没有办法在这些等待中包含“或”或使try/except块看起来更好?


Tags: 代码标题站点title网站sessionselenium条件
1条回答
网友
1楼 · 发布于 2024-04-29 14:02:26

看起来selenium可以通过创建自己的类来实现这一点。请在此处查看文档:http://selenium-python.readthedocs.io/waits.html

下面是一个简单的例子。注意,关键是在类中有一个名为__call__的方法来定义所需的检查。Selenium将每隔500毫秒调用该函数,直到它返回True或一些非null值。在

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))

相关问题 更多 >