gpt4 book ai didi

python - 带有 python : driver. 标题的 selenium 与实际页面标题不同

转载 作者:行者123 更新时间:2023-11-30 22:47:14 26 4
gpt4 key购买 nike

我在 python 上编写了一段代码,它必须检查加载的页面是否具有预期的标题。但在页面加载后,行 print(driver.title)打印出“Google”,而不是预期的“dog - Google Search”,您可以在页面源代码 ( <title> dog - Google Search </title> ) 上找到它。

问:为什么 driver.title 是“Google”,而不是标题标签之间的内容(“dog - Google Search”)?

这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

driver = webdriver.Firefox(executable_path = "/usr/local/bin/geckodriver")
driver.get("https:www.google.com") # opens the browser
# finds an input field and paste "dog" into it and then presses "Return"
search_field = driver.find_element_by_name("q")
search_field.send_keys("dog")
search_field.send_keys(Keys.RETURN)


# waits until the title of the page appears)
WebDriverWait(driver, 100).until
(
EC.presence_of_element_located((By.XPATH, "/html/head/title"))

)

print(driver.title) # prints driver.title (in reality it prints "Google" not "dog - Google Search")

#checks if the title is "dog - Google Search"
if driver.title == "dog - Google Search":
print("It works!")
else:
print("NO JOB YET")

driver.close()

最佳答案

需要更改预期条件,因为在这种情况下 presence_of_element_ located 保持 true,因为搜索页面打开后标题仍然可见,因此它不会真正等待标题更新。相反,您应该等到标题中的文本更改为预期条件下的预期内容,如下所示。

WebDriverWait(driver, 10).until(
EC.text_to_be_present_in_element((By.XPATH, "/html/head/title"), "dog - Google Search")
)

这将轮询 DOM 10 秒,如果发现标题匹配,它将继续执行下一条指令。

请参阅Selenium docs on waits了解更多详情。

关于python - 带有 python : driver. 标题的 selenium 与实际页面标题不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40595929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com