文件上传
文件上传下载的联系html:
uplad.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>upload_file</title>
<link href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="row-fluid">
<div class="span6 well">
<h3>upload_file</h3>
<input type="file" name="file" />
</div>
</div>
</body>
<script src="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.js"></script>
</html>
打开上面的html长这样:
方法一
如页面的的元素标签是input如下下图:
可直接赋值send_keys输入
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("file:///C:/Users/WeiBing/Desktop/uplad.html")
aaa =driver.find_element_by_xpath("//*[@name='file']")
aaa.send_keys("D:/a.txt")//直接将文件输入
time.sleep(5)
driver.quit()
注意:有些页面是input标签也可能input失败,遇到这种情况也先不要捉急,可尝试将定位的路径再次向顶层移动,如://*[@id='kw']/div/st[2]/input
,可尝试//*[@id='sq']/a/abody/div/st[2]/input
,有的时候就会出现这种莫名其妙的问题,加一些路径就可以成功找到元素了
方法二
使用AutoIt来完成
下载AutoIt
下载安装完成后点击开始菜单可看到如下菜单
AutoIt Windows Info 用于帮助我们识Windows控件信息。
Compile Script to.exe 用于将AutoIt生成 exe 执行文件。
Run Script 用于执行AutoIt脚本。
SciTE Script Editor 用于编写AutoIt脚本。
1、首先打开AutoIt Windows Info 工具,鼠标点击Finder Tool,鼠标将变成一个小风扇形状的图标,按住鼠标左键拖动到需要识别的控件上。
打开后界面如下:
识别输入框控件
识别打开按钮
通过AutoIt Windows Info 获得以下信息。
窗口的title为“选择要加载的文件”,标题的Class为“#32770”。
文件名输入框的class 为“Edit”,Instance为“1” ,所以ClassnameNN为“Edit1”。
打开按钮的class 为“Button”,Instance为“1” ,所以ClassnameNN为“Button1”。
2、 根据AutoIt Windows Info 所识别到的控件信息打开SciTE Script Editor编辑器,编写脚本。
ControlFocus("打开","","Edit1")
WinWait("[CLASS:#32770]","",10)
ControlSetText("打开","","Edit1", $CmdLine[1]) # $CmdLine[1]是命令行参数用于接收需要上传的文件,跟脚本中的 os.system('D:\\AA.exe D:\\a.txt')对应
Sleep(2000)
ControlClick("打开","","Button1");#如果是下载我们可以找到按钮直接点击
或这样:
ControlFocus("打开","","Edit1")
WinWait("[CLASS:#32770]","",10)
ControlSetText("打开","","Edit1","D:\a.txt")
Sleep(2000)#毫秒
ControlClick("打开","","Button1");
ontrolFocus()方法用于识别Window窗口。WinWait()设置10秒钟用于等待窗口的显示,其用法与WebDriver 所提供的implicitly_wait()类似。ControlSetText()用于向“文件名”输入框内输入本地文件的路径。这里的Sleep()方法与Python中time模块提供的Sleep()方法用法一样,不过它是以毫秒为单位,Sleep(2000)表示固定休眠2000毫秒。ControlClick()用于点击上传窗口中的“打开”按钮。
AutoIt的脚本已经写好了,保存通过菜单栏“Tools”–>“Go” (或按键盘F5)来运行一个脚本吧!注意在运行时如下窗口处于打开状态。
3、脚本运行正常,保存到本地AA.au3,这里保存的脚本可以通过Run Script 工具将其打开运行,但我们的目的是希望这个脚本被Python程序调用,那么就需要将其生成exe程序。打开Compile Script to.exe工具,将其生成为exe可执行文件。
点击“Browse”选择upfile.au3
文件,点击“Convert”按钮将其生成为AA.exe
程序。
代码示例
from selenium import webdriver
import os import time
driver = webdriver.Chrome() driver.get("file:///C:/Users/WeiBing/Desktop/uplad.html")
driver.find_element_by_xpath("//*[@name='file']").click() #点击上传按钮,会弹出上传框
os.system('D:\\AA.exe D:\\a.txt') #执行前面生成的exe文件,D:\\a.txt上传
time.sleep(5)
driver.quit()
成功
文件下载
参考链接
也可以使用上面上传使用的autoit工具