1、selenium3 实现文件下载
from selenium import webdriver
import os
options = webdriver.ChromeOptions()
prefs = {'profile.default_content_settings.popups': 0, #设置为禁止弹出下载窗口
'download.default_directory': os.getcwd() #设置为文件下载路径
}
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(chrome_options=options)
driver.get("http://pypi.Python.org/pypi/selenium") #文件下载地址
driver.find_element_by_link_text("Download files").click() #切换到下载页面
driver.find_element_by_partial_link_text("selenium-3.141.0.tar.gz").click() #单击下载文件
2、selenium3 实现文件上传
目录结构
生成 upfile.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>
文件上传代码 — file_upload.py
from selenium import webdriver
import os, time
driver = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('./web_page/upfile.html') #获取upfile.html文件路径
#将路径转化为字符串
base_dir = str(file_path)
#对路径的字符串进行替换
file_path = base_dir.replace('\\','/')
# print(base_dir)
# print(file_path)
driver.get(file_path) #打开upfile.html文件
time.sleep(2)
# 定位上传按钮,添加本地文件
driver.find_element_by_name("file").send_keys(os.path.abspath('./web_page/upload_file.txt'))
time.sleep(5)
driver.quit()
参考资料:Selenium 2 自动化测试实战 基于Python语言/虫师编著
来源:oschina
链接:https://my.oschina.net/u/4274413/blog/4335328