【问题标题】:Selenium is not properly determining if a page has a <title> html tagSelenium 未正确确定页面是否具有 <title> html 标记
【发布时间】:2019-05-22 08:56:07
【问题描述】:

我试图让 Selenium 等到使用 Python 加载时出现网页的标题标签。

我尝试使用其他类型的 HTML 标记测试此代码,只有 &lt;body&gt; 标记没有导致错误。

wait = WebDriverWait(driver, 10)
driver.get(link)
wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'div')))

我希望代码能够完成,但出现以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/support/wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

【问题讨论】:

  • 该页面是否真的有任何div 元素?

标签: python selenium selenium-webdriver webdriverwait page-title


【解决方案1】:

如果你想访问页面标题,定位&lt;title&gt;标签不是理想的方式。

要打印标题,您需要针对以下任一预期条件诱导 WebDriverWait

  • title_contains(partial_title)
  • title_is(title)
  • 一个例子:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
    driver.get("https://www.google.com/")
    WebDriverWait(driver, 10).until(EC.title_contains("G"))
    print("Page title is: %s" %(driver.title))
    
  • 控制台输出:

    Page title is: Google
    

【讨论】:

    【解决方案2】:

    title 标签永远可见。不过,您可以等待它出现

    wait.until(EC.presence_of_element_located((By.TAG_NAME, 'title')))
    

    标题也有自己的预期条件,title_is()title_contains()。例如:

    wait.until(EC.title_is("Google"))
    

    您可以在documentation 中查看支持的预期条件的完整列表。

    【讨论】:

    • 哇非常感谢您的帮助!这绝对是一个令人头疼的问题。我应该更多地关注方法名称的实际含义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2017-10-16
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多