Selenium3 實現文件的上傳與下載


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>
View Code

文件上傳代碼 — 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語言/蟲師編著


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM