使用 Selenium 检查文本是否可见,Python

Check if text is visible with Selenium, Python

我正在制作一个脚本,它将填写表格以使用 Python 创建一个 Gmail 帐户。当用户名已被使用时,会显示一条消息。荷兰语:"Dez gebruikersnaam worst al gebruikt. Probeer been andere gebruikersnaam." 为了能够处理这个问题,我需要检测此消息何时可见,但我不知道该怎么做。如果有人能提供帮助,那就太好了

试试这个 代码:

from selenium import webdriver
import time

path = '/home/avionerman/Documents/stack'
driver = webdriver.Firefox(path)

driver.get('https://www.google.com/intl/nl/gmail/about/#')

try:
    print('locating create account button')
    create_account_button = driver.find_element_by_class_name('h-c-button')
except:
    print("error, couldn't find create account button")
try:
    create_account_button.click()
    print('navigating to creation page')
except:
    print('error navigating to creation page')
time.sleep(8)


handles = driver.window_handles
size = len(handles)

driver.switch_to.window(handles[1])
print(driver.title)



first_name_input = driver.find_element_by_id('firstName')
first_name_input.click()
first_name_input.send_keys("WhateverYouWant")

last_name_input = driver.find_element_by_id('lastName')
last_name_input.click()
last_name_input.send_keys("WhateverYouWant2")

username_input = driver.find_element_by_id('username')
username_input.click()
username_input.send_keys('papadopoulos')

pswd_input = driver.find_element_by_name('Passwd')
pswd_input.click()
pswd_input.send_keys('whateveryouwant')

pswd_conf_input = driver.find_element_by_name('ConfirmPasswd')
pswd_conf_input.click()
pswd_conf_input.send_keys('whateveryouwant')

next_button = driver.find_element_by_id("accountDetailsNext")
next_button.click()


# In the variable x I save the text that is included inside the specific xpath
x = driver.find_element_by_xpath("//*[@id='view_container']/form/div[2]/div/div[1]/div[2]/div[1]/div/div[2]/div[2]/div").text
print(x)

# I assert in order to check if the variable x has the proper text value (the expected one)
assert x == 'Dez gebruikersnaam worst al gebruikt. Probeer been andere gebruikersnaam.'


time.sleep(10)

这样一来,如果断言通过就意味着您看到了警告消息,在任何其他情况下邮件的用户名都是唯一的。所以,我写给你的那部分代码,你可以将它插入到 if 语句中,你可以随意处理它。如果您需要任何进一步的信息,请随时联系我。