验证硒中的标题即使网站标题正确也找不到元素

Verify title in selenium gives element not found even though website title is correct

您好,我对此很陌生,我尝试使用 selenium 和 python 来验证标题。我输入的标题是正确的,但代码无法识别它。我已经尝试了 3 种不同的方法,但我要么找不到元素,要么出现字符串 object 错误,要么断言失败,即使页面标题是正确的。我已经注释掉了我尝试过的前 2 个,但保留了它们,这样您就可以看到我尝试了什么并得到错误:

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\webdrivers\chromedriver.exe")

driver.get(url="http://demostore.supersqa.com/my-account/")
driver.implicitly_wait(5)
#assert "My account - DemoStore" in driver.title
#the above assert doesnt work gives element not found
#driver.title().contain("My account - DemoStore")
#the above assert doesnt work gets string object error
try:
assert 'My account - DemoStore' in driver.title
print('Assertion test pass')
except Exception as e:
print('Assertion test failed', format(e))

这里有 2 个问题:

  1. 预期标题内容中的减号 - 有问题。它不是 - 那里的标志。请copy-paste将网页中的预期标题内容直接添加到您的代码中,它会起作用!
  2. 此处缺少缩进。
    这应该会更好:
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
driver = webdriver.Chrome(executable_path="C:\webdrivers\chromedriver.exe")
wait = WebDriverWait(driver, 20)

driver.get(url="http://demostore.supersqa.com/my-account/")

#assert "My account - DemoStore" in driver.title
#the above assert doesnt work gives element not found
#driver.title().contain("My account - DemoStore")
#the above assert doesnt work gets string object error
try:
    title = driver.title
    assert 'My account – DemoStore' in title
    print('Assertion test pass')
except Exception as e:
    print('Assertion test failed', format(e))

driver.quit()