程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

ui自动化,多窗口切换

发布于2020-02-25 00:42     阅读(1577)     评论(0)     点赞(5)     收藏(2)


在页面操作的时候单击某个链接会弹出新的窗口,这时就需要切换到新打开的窗口进行操作,webdriver提供了switch_to.window()方法,可以实现在不同的窗口之间切换。下面以百度窗口为例。直接上代码。

class Page(object):
    '''基础类,用于页面对象的继承'''
    login_url = 'https://www.baidu.com/'
    def __init__(self,selenium_driver,base_url = login_url):
        self.base_url = base_url
        self.driver = selenium_driver

    def _open(self,url):
        url = self.base_url
        self.driver.get(url)
    def open(self):
        self._open(self.url)
    def find_element(self,*loc):
        return self.driver.find_element(*loc)
        
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
from selenium.webdriver.common.by import By
from time import sleep
from .daidu_page import Page
class Login(Page):
    #定位元素
    url = '/'

    xinwen_loc = (By.LINK_TEXT,'新闻')
    nvren_loc = (By.XPATH,'/html/body/div[2]/div[2]/div[2]/div/ul/li[11]/a')

    #调用

    def type_xinwen(self):
        self.find_element(*self.xinwen_loc).click()
    def type_nvren(self):
        self.find_element(*self.nvren_loc).click()


    def user_login(self):
        self.open()     #打开百度
        sreach_windows =self.driver.current_window_handle     #获取当前窗口句柄
        self.type_xinwen()     #打开百度新闻
        all_handles = self.driver.window_handles     #获取所有句柄

        self.type_nvren()    

        for handle in all_handles:      #遍历所有句柄
            if handle != sreach_windows:    #当句柄不等于百度句柄时
                self.driver.switch_to.window(handle)    #切换窗口到百度新闻句柄
                self.type_nvren()    #点击新闻女生模块
            sleep(6)     #等待6s查看结果
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
import unittest
from selenium import webdriver
from .baidu_object import Login
class Test_login(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(10)
        self.login = Login(self.driver)
    def tearDown(self):
        self.driver.quit()
    def user_login_verify(self):
        self.login.user_login()

    def test_1(self):
        self.user_login_verify()

if __name__ == '__main__':
    unittest.main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
发布了14 篇原创文章 · 获赞 1 · 访问量 371


所属网站分类: 技术文章 > 博客

作者:加班是一种习惯

链接:https://www.pythonheidong.com/blog/article/232972/022861e3102525c0a86f/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

5 0
收藏该文
已收藏

评论内容:(最多支持255个字符)