Skip to main content
 首页 » 编程设计

python之selenium 的 expected_conditions [Python]

2025年05月04日10soundcode

我想加载我的驱动程序,直到我的 current_url 包含“某物”。我尝试了以下代码:

self.url = self.driver.current_url 
try: 
    element = WebDriverWait(self.driver, 20).until(EC.title_contains("XXX", "YYY", "ZZZ")) 
except: 
    print "\n IMPERFECT URL \n" 
finally: 
    self.driver.quit() 

但这种方法使用标题搜索..我想检查我当前的 url 是否有可能的字符串集。我怎么做?我还想检查同一网址中的三组字符串。有人可以帮忙吗。我是 Selenium 的新手。

请您参考如下方法:

我不太明白您想执行的具体测试。无论如何,您可以传递一个可调用对象并测试您想要的任何东西。以下是测试当前 URL 中是否存在 google、blah 或 foo 的工作代码示例:

from selenium import webdriver 
from selenium.webdriver.support.ui import WebDriverWait 
 
driver = webdriver.Chrome("/home/ldd/src/selenium/chromedriver") 
 
driver.get("http://google.com") 
 
def condition(driver): 
    look_for = ("google", "blah", "foo") 
    url = driver.current_url 
    for s in look_for: 
        if url.find(s) != -1: 
            return True 
 
    return False 
 
WebDriverWait(driver, 10).until(condition) 
 
driver.quit() 

(很明显,Chrome驱动的路径要根据自己的情况进行调整。)

只要condition 的返回值为真值,等待就结束。否则,将引发 TimeoutException。如果您从 ("google", ...) 中删除 "google",您将得到一个 TimeoutException。