python+selenium 上传文件或者图片

来源:互联网 发布:软件测试方案实例 编辑:程序博客网 时间:2024/05/22 17:32

文件上传操作也比较常见功能之一,上传功能没有用到新有方法或函数,关键是思路。

上传过程一般要打开一个本地窗口,从窗口选择本地文件添加。所以,一般会卡在如何操作本地窗口添加上传文件。

其实,在selenium  webdriver 没我们想的那么复杂;只要定位上传按钮,通send_keys添加本地文件路径就可以了。绝对路径和相对路径都可以,关键是上传的文件存在。下面通地例子演示。


第一步:新建一个txt文件,把下面的代码复制进去,然后重命名为upload_file.html文件,将此文件放置与python文件目录相同的地方

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>




第二步写见.py文件:

upload.py

#coding=utf-8from selenium import webdriverimport os,timedriver = webdriver.Firefox()#脚本要与upload_file.html同一目录file_path =  'file:///' + os.path.abspath('upload_file.html')driver.get(file_path)#定位上传按钮,添加本地文件driver.find_element_by_name("file").send_keys('D:\\selenium_use_case\upload_file.txt')time.sleep(2)driver.quit()


其它有些应用不好找,所以就自己创建页面,这样虽然麻烦,但脚本代码突出重点。

这里找一139邮箱的实例,有帐号的同学可以测试一下~!

(登陆基础版的139邮箱,网盘模块上传文件。)

139upload.py

#coding=utf-8from selenium import webdriverimport os,timedriver = webdriver.Firefox()driver.get("http://m.mail.10086.cn")driver.implicitly_wait(30)#登陆driver.find_element_by_id("ur").send_keys("手机号")driver.find_element_by_id("pw").send_keys("密码")driver.find_element_by_class_name("loading_btn").click()time.sleep(3)#进入139网盘模块driver.find_element_by_xpath("/html/body/div[3]/a[9]/span[2]").click()time.sleep(3)#上传文件driver.find_element_by_id("id_file").send_keys('D:\\selenium_use_case\upload_file.txt')time.sleep(5)driver.quit()


虫师文献: 
selenium借助AutoIt识别上传(下载)详解 
http://www.cnblogs.com/fnng/p/4188162.html

#使用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')

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

0 0
原创粉丝点击