selenium实战 登录后跳转到外部网站,再从外部网站跳转回来 (UI-0106)分享(白月黑羽网站selenium自动化学习)

在这里插入图片描述

from selenium import webdriver
import  time
# 创建 Webwd 实例对象,指明使用chrome浏览器驱动
wd = webdriver.Chrome(r'D:\tools-work\chromedriver_win32\chromedriver.exe')

wd.implicitly_wait(5)#等待时间 一定要写
# 登录
wd.get('http://127.0.0.1:8047/mgr/sign.html')
wd.find_element_by_id('username').send_keys("byhy")
wd.find_element_by_id('password').send_keys("88888888")
wd.find_element_by_tag_name('button').click()
time.sleep(1)
#点击外链之前先保存本页面句柄-------------------------
mainwindow=wd.current_window_handle
# 点击打开白月黑羽窗口的链接
link = wd.find_element_by_xpath('//*[@id="root"]/footer/div/a').click()

# 寻找所选外链,表示我要点击外部的网站
for handle in wd.window_handles:
    wd.switch_to.window(handle)
    if '白月黑羽教Python' in wd.title:
        break
# # 窗口最大化
wd.maximize_window()
#找到栏目信息
texts = wd.find_elements_by_xpath('//*[@id="navbar-content"]//span')
text = [f.text for f in texts]
print(text)#打印出栏目数据
#回到登录页  也就是原来的页面===================
wd.switch_to.window(mainwindow)
wd.find_element_by_css_selector('span.hidden-xs').click()
wd.find_element_by_css_selector('.pull-right a.btn').click()
time.sleep(2)
if wd.current_url=="http://127.0.0.1/mgr/sign.html":
    print("成功退出登录")

在这里插入图片描述
备注:有问题可以留言,一起进步。谢谢,哪里不对或者可以优化,请指正。~~~

窗口互换例子分享
1、在打开的网页中,点击 链接 “访问bing网站” , 就会弹出一个新窗口,访问bing网址
2、回到原网站

from selenium import webdriver

wd = webdriver.Chrome(r'D:\tools-work\chromedriver_win32\chromedriver.exe')
wd.implicitly_wait(10)

wd.get('http://cdn1.python3.vip/files/selenium/sample3.html')
#点击外链之前先保存本页面句柄
mainwindow=wd.current_window_handle
# 点击打开新窗口的链接
link = wd.find_element_by_tag_name("a")
link.click()

# wd.title属性是当前窗口的标题栏 文本
print(wd.title)
for handle in wd.window_handles:
    # 先切换到该窗口
    wd.switch_to.window(handle)
    # 得到该窗口的标题栏字符串,判断是不是我们要操作的那个窗口
    if 'Bing' in wd.title:
        # 如果是,那么这时候WebDriver对象就是对应的该该窗口,正好,跳出循环,
        break
#返回原网页
wd.switch_to.window(mainwindow)

详情查看博客:http://www.python3.vip/tut/auto/selenium/frame/

猜你喜欢

转载自blog.csdn.net/weixin_41665637/article/details/112369955
今日推荐