selenium python (十四)上传文件的处理

时间:2022-06-11 02:51:20

#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'zuoanvip'

#上传过程一般要打开一个系统的windows窗口,从窗口选择本地文件添加。所以一般会卡在如何操作本地window窗口。解决的方法很简单,只需要定位到上传按钮,然后通过send_keys添加本地文件路径即可
from selenium import webdriver
import  os
import time

driver = webdriver.Firefox()

#打开上传页面
file_path = 'file:///'+os.path.abspath()
driver.get(file_path)

#定位上传按钮,添加本地文件
driver.find_element_by_name('file').send_keys('D:\\selenium_use_case\upload_file.text')

time.sleep(5)

==========================================================

upload_file.html

<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/bootstrapcombined.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/twitterbootstrap/2.3.2/js/bootstrap.min.js"></script>
</html>