Python Selenium 文件上传之SendKeys

时间:2023-03-09 15:21:27
Python Selenium 文件上传之SendKeys

昨天写了Web 文件下载的ui自动化,下载之后,今天就要写web 文件上传的功能了。

当然从折腾了俩小时才上传成功。下面写一下自己操作的步骤

首先网上说的有很多方法

如 input 标签的最好做了,直接定位到元素,然后再sendKeys("value")即可

<input id="file_name" class="text-1 w255" type="text" readonly="" value="" data-file=""/>

奈何研发的同学做成了 readonly  属性的input ,好了学了一点,这种属性的input就没办法 使用 sendkeys了。

只能换其他方法了,

使用 下面  webdriver for python模拟键盘操作

#下面的方式没有成功
#ActionChains(self.driver).send_keys(releaseFile).perform()
#Ctrl + a
# ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).perform()
# self.driver.implicitly_wait(5)
# ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
# self.driver.implicitly_wait(5)
# ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()
# time.sleep(2)
# ActionChains(self.driver).key_down(Keys.ENTER).perform()
#self.driver.find_element_by_xpath(".//*[@id='file_name']").send_keys(releaseFile)
          

发现鼠标实际操作的还是页面,而不是弹出的文件选择框,所以这种方式还是不行。

最后参考

Python selenium文件上传方法汇总

http://www.jb51.net/article/92678.htm

使用了 SendKeys,因为其他方法有的需要安装其他程序

首先要安装SendKeys库,可以用pip安装

pip install SendKeys

安装的过程遇到如下问题

Python Selenium 文件上传之SendKeys

此时需要到 http://aka.ms/vcpython27  下载

https://www.microsoft.com/en-us/download/details.aspx?id=44266

Python Selenium 文件上传之SendKeys

然后执行安装 sendkeys即可成功。

代码如下

#-*-coding:utf-8-*-
#Time:2017/7/1-15:47
#Author:YangYangJun #-*-coding:utf-8-*-import SendKeys #点击上传 下载附件
time.sleep(2)
self.driver.find_element_by_xpath(".//*[@id='down_bar_code_template']").click()
self.driver.implicitly_wait(5)
#releaseFile_Path = os.path.join(os.getcwd(),'test_data')
releaseFile = r'C:\PySpace\CMS\UiTest\test_data' + '\UI_Release01.xlsx'
time.sleep(2)
self.driver.implicitly_wait(5)
self.driver.find_element_by_css_selector(".webuploader-pick").click()
time.sleep(2)
#将路径输入
SendKeys.SendKeys(releaseFile)
time.sleep(2)
#确定路径输入
SendKeys.SendKeys("{ENTER}")
time.sleep(2)
#确定打开按钮
SendKeys.SendKeys("{ENTER}")
time.sleep(2)
self.driver.implicitly_wait(5)
#点击上传
self.driver.find_element_by_xpath(".//*[@id='file_upload_btn']").click()
time.sleep(6)
#提示信息, 上传成功
successTest = u"上传商品成功!"
get_reInfo = self.driver.find_element_by_xpath(".//*[@id='step_05']/ul/li[1]").text
if successTest == get_reInfo:
print u"上传成功!"
#点击查看商品
self.driver.find_element_by_xpath(".//*[@id='view_goods']").click()
drugList = ['阿奇霉素片']
#调用验证及删除函数
self.get_Verify(drugList)
else:
print u"上传失败!"
else:
print u"进入卖家中心失败"

效果如下图

Python Selenium 文件上传之SendKeys

第一个 模拟回车是为了确认输入的文件路径,第二个回车是为了确认点击打开按钮。

至此文件的上传功能就已经完成了。

网上说这种方式有些不稳定,有时间的话可以学习一下其他方法。