测试项目中遇到上传文件时打开windows窗口的问题,为了定位windows窗口,引入了pywin32.
如果利用pywin32需要import win32gui,win32con,win32api,还有比较难懂的代码,如下:
handle=win32gui.FindWindow("#32770","打开")ComboBoxEx32 = win32gui.FindWindowEx(handle,0,'ComboBoxEx32',None) ComboBox = win32gui.FindWindowEx(ComboBoxEx32,0,'ComboBox',None)Edit = win32gui.FindWindowEx(ComboBox,0,'Edit',None) # 上面三句依次寻找对象,直到找到输入框Edit对象的句柄button = win32gui.FindWindowEx(handle,0,'Button',None) # 确定按钮Bfile_path = 'C:\\Users\\Administrator\\Desktop\\file.txt'win32gui.SendMessage(Edit,win32con.WM_SETTEXT,None,file_path) # 往输入框输入绝对地址time.sleep(3)win32gui.SendMessage(handle,win32con.WM_COMMAND,1,button)
在学习代码的过程中,发现上传文件方法完全可以简化为一行代码。需要找到上传文件对应的input元素,然后使用send_keys()方法进行上传。
以163邮箱中的“添加附件”功能为例
#coding=utf-8from selenium import webdriverfrom time import sleepdriver=webdriver.Chrome()sleep(3)url = "https://mail.163.com/"driver.get(url)sleep(3)iframe=driver.find_element_by_xpath("//div[@id='normalLoginTab']/div[@class='loginWrap']/div[@id='loginDiv']/iframe")driver.switch_to_frame(iframe)driver.find_element_by_name("email").click()driver.find_element_by_name("email").send_keys("emailaddrl")driver.find_element_by_name("password").click()driver.find_element_by_name("password").send_keys("password")driver.find_element_by_id("dologin").click()sleep(3)#定位'写信'按钮driver.find_element_by_xpath("//div[@id='dvNavTop']/ul[@id='_mail_component_55_55']/li[@id='_mail_component_59_59']/span[@class='oz0']").click()#添加附件file_path="C:\\Users\\Administrator\\Desktop\\2018-11-20_1.jpg"driver.find_element_by_xpath("//div[@class='by0']//input[@class='O0']").send_keys(file_path)