问题
I'm trying to get Selenium to wait until the title tag of a web page is present when loading with Python.
I've tried testing this code with other types of HTML tags and only the <body>
tag didn't result in an error.
wait = WebDriverWait(driver, 10)
driver.get(link)
wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'div')))
I expected the code to evaluate to completion but I got the following error:
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:
回答1:
The title
tag is never visible. You can wait for its presence, though:
wait.until(EC.presence_of_element_located((By.TAG_NAME, 'title')))
The title also has its own expected conditions, title_is()
and title_contains()
. For example:
wait.until(EC.title_is("Google"))
You can review the complete list of supported expected conditions in the documentation.
回答2:
If you want to access the Page Title locating the <title>
tag is not the ideal way.
To print the title you need to induce WebDriverWait either for either of the following expected_conditions:
- title_contains(partial_title)
- title_is(title)
An example:
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))
Console Output:
Page title is: Google
来源:https://stackoverflow.com/questions/53892345/selenium-is-not-properly-determining-if-a-page-has-a-title-html-tag