需求:今天利用学习时间写了一段上传文件的自动化代码,本来想的是按照以前的思路直接找到上传按钮然后send_keys,但是在实际操作中,该方法并不可行,具体原因不明,咨询别人才知道大家针对这种情况适用的是selenium+au3的方式完成上传操作的
话不多少直接上代码:
# encoding:utf-8
"""
此功能主要实现发帖的自动化
"""
import win32api, win32pdhutil, win32con
import win32com.client
from win32com.client import Dispatch
from selenium import webdriver
import DengLuLei
from selenium.webdriver.common.action_chains import ActionChains
import unittest,time,re,sys
class FaTie(unittest.TestCase):
def setUp(self):
self.browser=webdriver.Firefox()
def testFaTie(self):
DengLuLei.DengLuLei().dengLu(self.browser)#调用登录方法,并把webdriver作为参数传递,在函数调用完成后此webdriver已被改变
br=self.browser
autoit = Dispatch("AutoItX3.Control")
str_filepath ="C:\\Users\\Administrator\\Desktop\\ces\\c672f8b0b7d0a20df486a8.jpg"
br.find_element_by_css_selector("dt.J_sidebar_forum_toggle").click()
br.find_element_by_link_text("python").click()
ActionChains(br).move_to_element(br.find_element_by_xpath("//div[@class=\"main_content\"]/div[3]/a")).perform()#使用achionchains的perform方法进行点击下拉列表中的值得操作
time.sleep(2)
br.find_element_by_link_text(u"普通帖").click()#使用achionchains的perform方法进行点击下拉列表中的值得操作
br.find_element_by_id("J_atc_title").send_keys(u"autoit方式上传文件2")
br.find_element_by_xpath("//ul[@class='wind_editor_icons']/li[3]/div[3]/span").click()
br.find_element_by_id("SWFUpload_0").click()
autoit.WinWait(u"打开", "", 5)
autoit.WinActivate(u"打开")
autoit.ControlSetText(u"打开","","[CLASS:Edit; INSTANCE:1]",str_filepath)
autoit.ControlClick(u"打开","",1) #附件上传动作
time.sleep(4)
br.find_element_by_css_selector("button.edit_menu_btn").click()
cotent=u"这是我使用js处理的富文本编辑器12"
js="document.getElementsByClassName(\"wind_editor_iframe\")[0].contentWindow.document.body.innerHTML=\"%s\"" %(cotent)#此js可以解决富文本框编辑的问题,document.getElementsByClassName(\"wind_editor_iframe\")[0].contentWindow.document.body.innerHTML此段代码先通过classname获取iframe,随后通过获取当前的iframe的对象往body里写数据
br.execute_script(js)
br.find_element_by_id("J_post_sub").click()
time.sleep(5)
br.find_element_by_link_text(u"首页").click()
def tearDown(self):
pass
if __name__ == "__main__":
suite = unittest.TestSuite()
suite.addTest(FaTie("testFaTie"))
runner = unittest.TextTestRunner()
runner.run(suite)注释: autoit.WinWait(u"打开", "", 5)
autoit.WinActivate(u"打开")
autoit.ControlSetText(u"打开","","[CLASS:Edit; INSTANCE:1]",str_filepath)
autoit.ControlClick(u"打开","",1) #附件上传动作这段代码主要是操作au3的,具体的各个函数的使用方法可以参考一下au3的帮助文档,给大家的建议就是认真查一下这些方法的文档解释,先按照文档把功能实现,然后再继续深入的理解各个参数的含义,一个小时应该可以搞定,我是因为走了一个误区,所以搞了三个多小时,浪费啊
备注:
大家在selenium中使用au3的时候首先需要安装win32api这个东西,具体的下载地址可以在网上搜一下,安装完成之后最好重启一下代码编辑器,然后导入
import win32api, win32pdhutil, win32con
import win32com.client
from win32com.client import Dispatch这三个模块,最后再导入之后需要在代码中调用一下au3,代码是:autoit = Dispatch("AutoItX3.Control")搞定之后大家就可以很爽的在selenium中调用au3了
本文介绍了如何结合selenium、python和AutoIt来解决在自动化测试中遇到的文件上传问题。传统的selenium send_keys方法在此场景下无法正常工作,作者通过引入AutoIt库,并提供了相关代码示例,详细解释了安装和使用步骤。

3203

被折叠的 条评论
为什么被折叠?



