selenium+python:脚本学习笔记(一)

来源:互联网 发布:熊猫网络电视怎么用 编辑:程序博客网 时间:2024/05/16 17:39
  • 切换frame定位元素

Firepath不显示Top Window,说明你要定位的目标元素在一个iframe里,如果要操作这个元素,首先需要从默认的Top Window,利用switch_to.frame('iframeid')方法来切换到具体的iframe,然后才能去操作目标元素。

driver.switch_to.default_content() 

driver.switch_to.frame("maintopFrame")
  • autoIT帮助操作非浏览器弹框
autoIT代码:
;ControlFocus("title","text",controlID) Edit1=Edit instance 1
ControlFocus("Windows 安全", "","Edit1"
; Wait 10 seconds for the Upload window to appear
WinWait("[CLASS:#32770]","",10)
; Set the File name text on the Edit field
ControlSetText("Windows 安全", "", "Edit1", "duo.zhang")
Sleep(1000)
ControlSetText("Windows 安全", "", "Edit2", "test.123")
Sleep(1000)
; Click on the Open button
ControlClick("Windows 安全", "","Button2");
python调用代码:
os.system("D:\\login.exe")
  • 页面汉字显示判断
        #页面指定位置是否存在某字符串
        abc=self.driver.find_element_by_id("lastTimeDiv").text
        if u'上次登录时间' in abc:
             print ('Assertion test pass0.')
        else: 
             print ('Assertion test fail0.')        
        #使用断言判断
        self.assertEqual(self.driver.find_element_by_id("lastTimeDiv").text,u'上次登录时间','未显示')
        #在页面上是否存在指定字符串,不指定位置  
        try: 
            assert u"上次登录时间" in driver.page_source 
            print ('Assertion test pass1.') 
        except Exception as e: 
             print ('Assertion test fail1.', format(e)) 
            
         #在页面标题上是否存在指定字符串   
        if u"上次登录时间" in driver.title : 
             print ('Assertion test pass2.') 
        else: 
             print ('Assertion test fail2.') 
        # 直接把字段写入XPath表达式,如果通过该XPath能定位到元素,说明这个错误字段已经在页面显示 
        try : 
            error_message = driver.find_element_by_xpath(".//*[@id='datagrid-row-r1-2-0']/td[1] and text()='模块访问统计'").is_displayed() 
            print ("Test pass. the 模块访问统计  is display.") 
        except Exception as e: 
            print ("Test fail.", format(e)) 
        # 通过该目标元素节点,然后通过element.text得到值,在拿得到的text值取和期待的结果去字符串匹配
        mes1 = driver.find_element_by_css_selector("#datagrid-row-r1-2-0 > td > div.datagrid-cell.datagrid-cell-c1-ModuleName").text 
        try: 
            assert mes1 == u'模块访问统计' 
            print ('模块访问统计 Test pass.') 
        except Exception as e: 
             print ("Test fail.", format(e)) 
  • select框选择
         #定位下拉枚举值-----先定位select框,再定位select里的选项
        try: 
             driver.find_element_by_id("MainContent_ddlLevel").find_element_by_xpath("//option[@value='B+']")
             print ('枚举值B+ test pass.')
        except Exception as e: 
             print ('枚举值B+ test fail1.', format(e))
        #定位下拉枚举值---直接定位
        s1=driver.find_element_by_xpath(".//*[@id='MainContent_ddlLevel']/option[@value='B-']").text
        if len(s1) == 0:
            print ("枚举值B-未找到 test fail")
        else:
            print ("枚举值B-找到 testpass")
        #driver.find_element_by_xpath(".//*[@id='MainContent_ddlLevel']/option[@value='B-']").click()
        # 选取枚举值:select模块定位select下拉枚举值
        s2 = driver.find_element_by_id("MainContent_ddlLevel")
        Select(s2).select_by_visible_text("B")
       
        # 采用遍历方式,遍历select下的枚举值
        s3= driver.find_element_by_id("MainContent_ddlLevel")
        options_list=s3.find_elements_by_tag_name("option")
        for option in options_list:
            print ("Value is: " + option.get_attribute("value"))
            print ("Text is:" +option.text)
            if "B-" in option.text:
                select_value=option.get_attribute("value")
                print ("已找到下拉列表值: " + select_value)
                break
  • 关于时间
        from datetime import datetime
        timeStr=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  • 关于截取字符串
        import operator
       try:
            assert operator.eq(timeStr[0:18], mes3[0:18])==True
            print ("访问时间正确")
        except Exception as e:   
            print ("访问时间正确Test fail.", format(e))
  • 关于控制台输出与日志输出
Logger.py
#coding=utf-8
import logging
import logging.handlers  
 
class Logger(): 
       
    def __init__(self, logName1, logger): 
     
            logDir=r"D:\test" 
            logName = logDir + r"\\" + logName1
            fh = logging.FileHandler(logName) 
            self.logger = logging.getLogger(logger) 
            self.logger.setLevel(logging.DEBUG) 
            #fh = logging.FileHandler(logName) 
            fh.setLevel("NOTSET") 
     
 
            ch = logging.StreamHandler() 
            ch.setLevel("NOTSET") 
     
 
            log_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s  -[%(filename)s:%(lineno)d]') 
            fh.setFormatter(log_format) 
            ch.setFormatter(log_format) 
     
     
            self.logger.addHandler(fh) 
            self.logger.addHandler(ch) 
        
    def getlog(self): 
            return self.logger 
其它py使用
from Logger import * 
logger = Logger(logName1='log1.txt',logger="supplierInfo.py").getlog()
#以下内容能同时在控制台和log.txt中显示
logger.info('供应商英文名 test pass.')