Python Selenium:如何等到 href 属性包含特定字符串?

Python Selenium: How to wait until href attribute contains a specific string?

例如,我在 Selenium 中打开页面 https://example.com/page-1/,寻找包含 domain.com 的特定 link。现在我正在使用 sleep(20) 来确保页面已完全加载。但我想知道我是否可以使用 WebDriverWait 不仅用于标记存在,而且还用于它的包含存在。尚未找到任何解决方案...

您可以尝试这样的操作,我假设您使用的是 Firefox,但逻辑是相同的:

firefox = webdriver.Firefox()
firefox.get('https://example.com/page-1/')
#wait for a maximum of 60 seconds in this example
wait = WebDriverWait(firefox, 60)
domain = "domain.com"
wait.until(lambda x: x.find_element_by_css_selector(f"a[href*='{domain}']"))

等待 for the href attribute to contain a specific string, you can induce for the visibility_of_element_located() and you can use either of the following :

  • domain.com的完全匹配:

    • 使用CSS_SELECTOR:

      element = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a[href='domain.com']")))
      
    • 使用XPATH:

      element = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@href='domain.com']")))
      
  • domain.com的部分匹配:

    • 使用CSS_SELECTOR:

      element = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a[href*='domain.com']")))
      
    • 使用XPATH:

      element = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[contains(@href, 'domain.com')]")))
      
  • 注意:您必须添加以下导入:

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