发布于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)
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查看结果
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()
作者:加班是一种习惯
链接:https://www.pythonheidong.com/blog/article/232972/022861e3102525c0a86f/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!