前提:1. 在当前目录下放HTML文件: upload.html; 2. 再放一个上传的测试文件:upload_pic.png
一、上传文件
1、借用send_keys()的方式
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>hello</title> </head> <body> <form action="testform.php"method="get"> 请选择上传的多个文件: <input type="file" name="img"multiple="" /> </body> </html>
注意:只有input标签下的type等于file才可以使用send_keys的方式
具体如下:
from selenium import webdriver from selenium.webdriver.common.by import By from time import sleep from os.path import abspath,dirname driver = webdriver.Chrome() driver.maximize_window() file_path = dirname(abspath(__file__)) #abspath获取当前文件的绝对路径, dirname获得上级目录 upload_page = file_path+r'upload.html' #拼接html文件的路径 upload_pic = file_path+r'upload_pic.png' driver.get(upload_page) sleep(2) driver.find_element(By.NAME,'img').send_keys(upload_pic) #定位到上传按钮,并且传文件路径给它
sleep(2)
driver.quit()
2、AutoIT插件上传文件 (当上传按钮不在input标签中时)
参考文章:https://blog.csdn.net/qq_36800800/article/details/82189143
二、下载文件
# -*- coding: utf-8 -*- from selenium import webdriver from time import sleep import os options = webdriver.ChromeOptions() prefs = {'profile.default_content_settings.popups': 0, 'download.default_directory': os.getcwd()} #download.default_directory:设置下载路径 #profile.default_content_settings.popups:设置为 0 禁止弹出窗口 options.add_experimental_option('prefs', prefs) driver = webdriver.Chrome( chrome_options=options) driver.maximize_window() driver.get("https://pypi.org/project/selenium/#files") sleep(2) driver.find_element_by_partial_link_text("selenium-3.141.0.tar.gz").click() sleep(3) ''' #下面是通过FireFox的方式 from selenium import webdriver fp = webdriver.FirefoxProfile() fp.set_preference("browser.download.folderList", 2) fp.set_preference("browser.download.manager.showWhenStarting", False) # 不起作用 fp.set_preference("browser.download.dir", os.getcwd()) fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream") driver = webdriver.Firefox(firefox_profile=fp) driver.get("http://pypi.Python.org/pypi/selenium") driver.find_element_by_partial_link_text("selenium-3.11.0-py2.py3-none-any").click() '''