📜  如何使用Python在selenium中访问弹出登录窗口

📅  最后修改于: 2022-05-13 01:54:23.209000             🧑  作者: Mango

如何使用Python在selenium中访问弹出登录窗口

许多网站使用社交媒体登录来简化用户的登录过程。在大多数情况下,如果单击按钮,则会打开一个新的弹出窗口,用户必须在其中输入其用户凭据。可以在浏览器中手动切换窗口并输入所需的凭据进行登录。但在使用 webdriver 进行无人值守 Web 访问的情况下,驱动程序无法自动切换窗口。我们需要更改驱动程序中的窗口句柄以在弹出窗口中输入登录凭据。 Selenium具有切换窗口以使用同一驱动程序访问多个窗口的函数。
首先,我们必须从 webdriver 获取当前窗口句柄,这可以通过以下方式完成:

driver.current_window_handle

我们需要保存它以获取当前窗口句柄。弹出窗口出现后,我们必须立即获取所有可用窗口句柄的列表。

driver.window_handles

然后我们可以从这个列表中获取登录页面的窗口句柄,然后切换控件。要切换窗口句柄,请使用:

driver.swtich_to.window(login_page)

成功登录后,我们可以使用相同的 switch_to 方法将控制切换到上一页。
注意:要运行此代码selenium库和geckodriver for firefox 是必需的。 selenium的安装可以使用Python第三方库安装程序 pip 来完成。要安装selenium ,请运行此命令

pip install selenium

对于 geckodriver,下载文件并将其路径添加到 OS PATH 变量中,以便可以从文件目录中的任何位置激活它。
让我们看看使用 Facebook 登录 zomato.com 的代码。

Python3
# import the libs
from selenium import webdriver
from time import sleep
 
# create the initial window
driver = webdriver.Firefox()
 
# go to the home page
driver.get('https://www.zomato.com')
 
# storing the current window handle to get back to dashboard
main_page = driver.current_window_handle
 
# wait for page to load completely
sleep(5)
 
# click on the sign in tab
driver.find_element_by_xpath('//*[@id ="signin-link"]').click()
 
sleep(5)
 
# click to log in using facebook
driver.find_element_by_xpath('//*[@id ="facebook-login-global"]/span').click()
 
# changing the handles to access login page
for handle in driver.window_handles:
    if handle != main_page:
        login_page = handle
         
# change the control to signin page       
driver.switch_to.window(login_page)
 
# user input for email and password
print('Enter email id : ', end ='')
email = input().strip()
print('Enter password : ', end ='')
password = input().strip()
 
# enter the email
driver.find_element_by_xpath('//*[@id ="email"]').send_keys(email)
 
# enter the password
driver.find_element_by_xpath('//*[@id ="pass"]').send_keys(password)
 
# click the login button
driver.find_element_by_xpath('//*[@id ="u_0_0"]').click()
 
 
 
# change control to main page
driver.switch_to.window(main_page)
 
sleep(10)
# print user name
name = driver.find_element_by_xpath('/html/body/div[4]/div/div[1]/header/div[2]/div/div/div/div/span').text
print('Your user name is : {}'.format(name))
 
# closing the window
driver.quit()


输出: