使用Selenium填充此站点的用户名和密码



我试图通过GUI打开网站,在Python上使用自动登录功能。我可以打开网站("https://iam.bethel.edu")没有任何问题。我知道使用Selenium,您可以选择操纵站点来填充用户名/密码框(我曾经实习过的一个家伙就是这样做的)。

然而,我似乎不能把文本输入用户名或密码字段,因为我一直得到一个NoSuchElementException。我是不是漏掉了什么find_element()方法?

我代码:

def open_IAM(self):
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options, executable_path='.ChromeDriver.exe')
driver.get("https://iam.bethel.edu")
driver.find_element(By.NAME, "input-box").send_keys('username', Keys.TAB, 'password!', Keys.ENTER)

与Instagram网站一起使用的其他代码:

browser.find_element(By.NAME, 'username').send_keys('MYEMAIL', Keys.TAB, 'MYPW', Keys.ENTER)

usernamepassword元素嵌入在iframe中。因此,为了与这些元素交互,你必须切换到iframe.

这是一个非常粗略的代码片段。

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
class Login:
def __init__(self, username, pwd):
self.username = username
self.pwd = pwd
self.url = 'https://iam.bethel.edu/idmdash/#/default'
self.chromeDriver_dir = r"Your chrome exe dir" # put in your value
self.iframe_id = 'oauthframe' # fixed don't change
self.uname_id = 'Ecom_User_ID'# fixed don't change
def _launch_website(self):
self.chrome = webdriver.Chrome(service=Service(self.chromeDriver_dir))
self.chrome.maximize_window()
self.chrome.get(self.url)
def _switch_iframe(self): # this is the part you should add to your code
iframe = WebDriverWait(self.chrome, 10).until(EC.presence_of_element_located((By.ID, self.iframe_id)))
self.chrome.switch_to.frame(iframe)
def _input_username_pwd(self):
uname = WebDriverWait(self.chrome, 10).until(EC.presence_of_element_located((By.ID, self.uname_id)))
login_chain = ActionChains(self.chrome)
login_chain.click(uname).send_keys(self.username).send_keys(Keys.TAB)
login_chain.send_keys(self.pwd).perform()
def login(self):
self._launch_website()
self._switch_iframe()
self._input_username_pwd()
time.sleep(20) # Just to ensure everything worked. 

if __name__ == '__main__':
Login(username='ABC', pwd='EFG').login()

最新更新