selenium+python 上传文件
使用send_keys()方法,跟一个本地的文件路径,到达上传文件目的。
(备注:该例子是根据‘虫师’例子做了补充)
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/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>
script:
#-*-coding:utf-8-*-
from selenium import webdriver
import os
import time
driver = webdriver.Firefox()
file_path = 'file:///'+os.path.abspath('upload_file.html')
driver.get(file_path)
#使用send_keys('绝对路径')方法上传文件
#driver.find_element_by_name('file').send_keys('C:\Users\Think\Pictures\file\note_book.jpg')
#使用send_keys('相对路径')方法上传文件
driver.find_element_by_name('file').send_keys('C:\\\Pictures\\note_book.jpg')
time.sleep(2)
driver.quit()
在这里主要强调的是绝对路径与相对路径的使用。
虫师文献:
selenium借助AutoIt识别上传(下载)详解
http://www.cnblogs.com/fnng/p/4188162.html