如何使用Python/Selenium Webdri断言/验证成功登录

2024-06-06 13:27:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一些研究,但没有找到任何特定于使用Python的Selenium WebDriver的答案。 我可以成功登录到页面,但无法找到验证登录是否成功的方法。页面标题不适合我,因为它不会更改。 PythonSelenium文档没有任何好的解释或示例。 在这段代码之后,我所要做的就是在页面上放置一行并断言用户名“Tuto”是可见的

LoginButtonLocator = "//a[contains(text(), 'Login')]"
facebookConnectButtonLocator = "//a[contains(text(), 'Connect with Facebook')]"

facebookLoginLocatorID = "email"
facebookPasswordLocatorID = "pass"
facebookLoginButtonLocatorID = "loginbutton"

LoginButtonElement = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath(LoginButtonLocator))
LoginButtonElement.click()
facebookConnectButtonElement = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath(facebookConnectButtonLocator))
facebookConnectButtonElement.click()
facebookLoginElement = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_id(facebookLoginLocatorID))
facebookLoginElement.send_keys(facebookID)
facebookPasswordElement = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_id(facebookPasswordLocatorID))
facebookPasswordElement.send_keys(facebookPW)
facebookLoginButtonElement = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_id(facebookLoginButtonLocatorID))
facebookLoginButtonElement.click()

Tags: lambdatextidbydriver页面elementfind
2条回答

我使用的是Javascript API而不是Python版本,因此语法有所不同,但是我将如何实现它(使用mocha作为测试框架):

facebookLoginButtonElement.click().then(function(_) {
    driver.findElement(By.xpath('//a[text() = "Tuto"]')).then(function(userLink) {
        assert.ok(userLink);
    });
});

在javascript版本中,如果找不到<a ...>Tuto</a>,则在调用回调之前会出现一个错误,因此断言是多余的(只有在找到链接时才会到达),但我发现它是自文档化的,所以我添加了assert。在

只需尝试使用xPath查找元素:

wait = WebDriverWait(browser, 10) 

find_username = wait.until(EC.presence_of_element_located((By.XPATH,'//span[contains(text(), "Alex")]')))

assert find_username

希望,它会帮助你。在

相关问题 更多 >