Python+Selenium-上传文件

Python+Selenium学习--上传文件

场景

文件上传操作也比较常见功能之一,上传功能操作webdriver 并没有提供对应的方法,关键上传文件的思路。
上传过程一般要打开一个系统的window 窗口,从窗口选择本地文件添加。所以,一般会卡在如何操作本地window 窗口。其实,上传本地文件没我们想的那么复杂;只要定位上传按钮,通send_keys 添加本地文件路径就可以了。绝对路径和相对路径都可以,关键是上传的文件存在。

代码

upload_file.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>upload_file</title>
<script type="text/javascript" async=""
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css"
rel="stylesheet" />
<script type="text/javascript">
</script>
</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://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</html>               

  

python代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#coding=utf-8
from selenium import webdriver
import os,time
driver = webdriver.Firefox()
 
#打开上传文件页面
file_path = 'file:///' + os.path.abspath('upload_file.html')
driver.get(file_path)
 
#定位上传按钮,添加本地文件
driver.find_element_by_name("file").send_keys('D:\selenium_use_caseupload
_file.txt')
 
time.sleep(2)
driver.quit()
原文地址:https://www.cnblogs.com/chenlimei/p/12780753.html