许多网站使用社交媒体登录来简化用户的登录过程。在大多数情况下, 如果单击该按钮, 则将打开一个新的弹出窗口, 用户必须在其中输入用户凭据。可以手动在浏览器中切换窗口并输入所需的凭据以登录。但是, 如果使用webdriver进行无人值守的Web访问, 则驱动程序不能仅自动切换窗口。我们需要更改驱动程序中的窗口句柄, 以便在弹出窗口中输入登录凭据。Selenium具有使用同一驱动程序切换窗口以访问多个窗口的功能。
首先, 我们必须从Webdriver获取当前的窗口句柄, 这可以通过以下方式完成:
driver.current_window_handle
我们需要保存它以获取当前的窗口句柄。弹出窗口出现后, 我们必须立即获取所有可用窗口句柄的列表。
driver.window_handles
然后, 我们可以从该列表中获取登录页面的窗口句柄, 然后切换控件。要切换窗口句柄, 请使用:
driver.swtich_to.window(login_page)
成功登录后, 我们可以使用相同的切换到将控件更改为上一页的方法。
注意:要运行此代码硒库, 并壁虎对于Firefox是必需的。可以使用Python第三方库安装程序来完成selenium的安装点子。要安装硒, 请运行以下命令
pip install selenium
对于geckodriver, 请下载文件并将其路径添加到OS PATH变量中, 以便可以从文件目录中的任何位置激活它。
让我们看看使用Facebook在zomato.com上登录的代码。
# 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 dashbord
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()
输出如下:
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
来源:
https://www.srcmini02.com/68384.html