如何在Selenium中验证电子邮件用户输入?

2024-04-25 12:05:42 发布

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

我正在使用selenium设置一个自动浏览器。我需要用户输入来完成表单,其中一个字段是需要有效的email。你知道吗

我已经查过了,没有找到匹配的

print(Fore.RED + (" "*7) + " | " + Fore.WHITE + "Email Adress: " + Style.RESET_ALL, end='')
email = input()


chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")

driver = webdriver.Chrome(chrome_options=chrome_options)

没有结果


Tags: 用户表单styleemailselenium浏览器redchrome
1条回答
网友
1楼 · 发布于 2024-04-25 12:05:42

验证电子邮件的最简单方法是使用regular expression。我发现了一个预先制作的here,但是如果你需要国际字符支持或其他细节,你可以在网上使用很多其他的。你知道吗

您需要导入re库才能在python中使用regex。^如果字符串满足正则表达式,{}将返回Match object(其值为true),否则返回false。你知道吗

这是我的实现。请注意,即使电子邮件无效,程序也会继续执行。您可以选择使用while循环并不断提示用户直到输入有效的电子邮件,或者在else子句中引发异常以终止程序。你知道吗

from colorama import Fore, Style
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import re

print(Fore.RED + (" "*7) + " | " + Fore.WHITE +
      "Email Adress: " + Style.RESET_ALL, end='')
email = input()

if re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email): # if the email is valid
    print("That's a valid email!")
else:
    print("That's an invalid email!") # or raise exception to stop execution 

# do Selenium stuff
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(" incognito")

driver = webdriver.Chrome(options=chrome_options)

编辑:以下是我将如何循环,直到电子邮件是有效的。。。你知道吗

email_flag = False
while not email_flag:
    # prompt for email + get input
    print(Fore.RED + (" "*7) + " | " + Fore.WHITE +
      "Email Adress: " + Style.RESET_ALL, end='')
    email = input()

    # validate user input
    if re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email):  # if the email is valid
        print("That's a valid email!")
        email_flag = True
    else:  # the email is invalid
        print("That's an invalid email!")
        # allow email_flag to remain false

相关问题 更多 >