Selenium Basics - File Upload & File Download

File Upload

Description:
File upload is a very common function on web pages, and it is very simple to use scripts to realize file upload.
General scenario: The upload button on the page is an <input> tag, where the type attribute is type="file", which can be easily solved with the method provided by seleniumsend_keys() .
Example:
Page code snippet:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
</head>
<body>
<fieldset>
    <legend>文件上传</legend>
    <form action="">
        <input type="file" name="upfile" value="">
    </form>
</fieldset>
</fieldset>
</body>
</html>

Script code:

"""
1.学习目标:
    掌握文件上传功能操作
2.操作步骤
    此上传方式适用大多数情况。
    上传文件标签为input类型,并且type=file时可使用此方式上传。
    使用send_keys(“需要上传的文件的路径")
3.需求
    在页面中,实现文件上传
4.总结
    4.1 在上传文件的时候,对文件类型,大小等做充分验证。
    4.2 在执行上传文件脚本时,加一定的等待时间,sleep()。
    4.3 大多数上传文件都是input类型并且type=file。
    4.4 对于非input标签的上传文件功能,使用Sendkeys库来实现。
"""
# 1.导入selenium
from selenium import webdriver
from time import sleep
import os
 
# 2.打开浏览器
driver = webdriver.Chrome()
 
# 3.打开注册A页面
url = "file:///" + os.path.abspath("./1.html")
driver.get(url)
sleep(2)
 
# 4.上传文件
# 4.1 定位上传文件按钮
upfile = driver.find_element_by_name("upfile")
 
# 4.2 使用send_keys方法上传文件
upfile.send_keys(r"C:\Users\L\Desktop\测试上传文件.txt")
sleep(5)
 
# 5.关闭浏览器
driver.quit()

 Tip:
Another non-<input> tag upload file button is more difficult to implement, and can be implemented with the help of the autoit tool or the SendKeys third-party library.
The upload process generally requires opening a system window, and selecting a local file to add from the window. Therefore, it is generally stuck on how to operate the local window window.

Summary:
In fact, uploading local files is not as complicated as we thought. Just locate the upload button and send_keys()add the local file path by method. Both absolute path and relative path are available, the key is that the uploaded file exists.
Small exercise: use the mailbox to send an email to other people in place of attachments. To add an attachment is to upload a file. The operation of the mail body is to operate the iframe element. 

Download Document

To use selenium.webdriverthe function of downloading files, you only need to configure the parameters of the browser to realize it.
1. Firefox browser file download
steps:

  • For Firefox, we need to set its Profile: Create a Firefox custom configuration information instance through the FirefoxProfile() method.
  • Set the Firefox browser to download related custom configuration information to the Profile instance.
  • Start Firefox and store the custom configuration Profile instance in the browser object.
  • Visit the download site to download.

 Example:
Requirement: Download the Firefox browser driver file

"""
1.学习目标
    了解使用火狐浏览器实现文件下载
2.操作步骤(语法)
    2.1 创建Firefox浏览器配置信息对象
        webdriver.FirefoxProfile()
    2.2 设置Firefox浏览器下载相关的自定义配置信息
    2.3 创建Firefox浏览器对象,并把自定义配置信息存储到浏览器对象中
    2.4 访问下载网站
    2.5 进行下载
3.需求
    使用火狐浏览器实现文件下载
"""
# 1.导入selenium
from selenium import webdriver
from time import sleep
 
# 2.创建Firefox浏览器配置信息对象,用于存放自定义配置
profile = webdriver.FirefoxProfile()
 
# 3. 配置profile下载相关信息
"""
3.1 指定自定义下载路径,默认只会自动创建一级目录,
    如果指定了多级不存在的目录,将会下载到默认路径,
    如下就是定义了多级不存在的目录,文件就下载到了火狐浏览器的默认下载目录中
    我的火狐默认下载路径:C:\\Users\\L\\Downloads
"""
profile.set_preference('browser.download.dir', 'f:\\Download\\123\\456')
 
"""
3.2 将browser.download.folderList设置为:
    设置成 0 表示下载到桌面
    设置成 1 表示下载到浏览器默认下载路径
    设置成 2 表示使用自定义下载路径
    
    和上面browser.download.dir配合使用,如果设置成0和1
    上面的配置基本无用。
"""
profile.set_preference('browser.download.folderList', 2)
 
"""
3.3 browser.helperApps.alwaysAsk.force:
    对于未知的 MIME 类型文件会弹出窗口让用户处理,
    默认值为true,设定为False,
    表示不会记录打开未知 MIME 类型文件的方式
"""
profile.set_preference("browser.helperApps.alwaysAsk.force", False)
 
"""
3.4 在开始下载时是否显示下载管理器
    设定为true,则在用户启动下载的时候显示Firefox浏览器的文件下载窗口
    否则不显示文件下载窗口。
"""
profile.set_preference('browser.download.manager.showWhenStarting', False)
 
"""
3.5 设定为 False 会把下载框进行隐藏
"""
profile.set_preference("browser.download.manager.useWindow", False)
 
"""
3.6 默认值为 true,设定为 False 表示不获取焦点
"""
profile.set_preference("browser.download.manager. focusWhenStarting", False)
 
"""
3.7 下载.exe文件弹出警告,
    默认值是 true,设定为False 则不会弹出警告框
"""
profile.set_preference("browser.download.manager.alertOnEXEOpen", False)
 
"""
3.8 browser.helperApps.neverAsk.openFile:
    表示直接打开下载文件,不显示确认框
    默认值为空字符串,下行代码行设定了多种文件的 MIME类型.
    例如:
        application/exe,表示.exe类型的文件,
        application/excel表示 Excel 类型的文件
"""
profile.set_preference("browser.helperApps.neverAsk.openFile", "application/zip")
 
"""
3.9 对所给出文件类型不再弹出框进行询问,直接保存到本地磁盘
"""
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/zip, application/octet-stream')
"""
其他可选文件类型:
    application/a-gzip
    application/x-gzip,
    application/zip,
    application/x-gtar,
    text/plain,
    application/x-compressed,
    application/octet-stream,
    application/pdf
"""
 
"""
3.10 browser.download.manager.showAlertOnComplete:
    设定下载文件结束后是否显示下载完成提示框,
    默认为true,设定为False,
    表示下载完成后不显示下载完成提示框
"""
profile.set_preference("browser.download.manager. showAlertOnComplete", False)
 
"""
3.11 browser.download.manager.closeWhenDone:
    设定下载结束后是否自动关闭下载框,
    默认值为true,设定为False,
    表示不关闭下载管理器.
"""
profile.set_preference("browser.download.manager.closeWhenDone", False)
 
# 4. 创建浏览器对象
# 启动浏览器时,通过firefox_profile参数
# 将自动以配置添加到FirefoxProfile对象中
driver = webdriver.Firefox(firefox_profile=profile)
 
# 5. 访问Firefox浏览器驱动文件下载网址
driver.get("https://npm.taobao.org/mirrors/geckodriver/v0.20.0/")
sleep(3)
 
# 6. 定位下载链接,并点击下载
file = driver.find_element_by_link_text("geckodriver-v0.20.0-win64.zip")
file.click()
sleep(3)
 
# 7.关闭浏览器
driver.quit()

2. Chrome browser file download
Example:
Chrome browser, set its options:

  1. download.default_directory: Set the download path.
  2. profile.default_content_settings.popups: Set to 0 to disable popups.
"""
1.学习目标
    了解使用谷歌浏览器实现文件下载
2.操作步骤(
    2.1 创建谷歌浏览器加载项对象
        webdriver.ChromeOptions()
    2.2 定义Chrome浏览器加载项参数
    2.3 将加载项参数添加到谷歌浏览器加载项对象中
        options.add_experimental_option('prefs', prefs)
    2.4 创建Chrome浏览器对象,并把自定义加载项对象存储到浏览器对象中
    2.5 访问下载网站
    2.6 进行下载
3.需求
    使用谷歌浏览器实现文件下载
"""
# 1.导入selenium
from selenium import webdriver
from time import sleep
 
# 2. 创建谷歌浏览器加载项对象
options = webdriver.ChromeOptions()
 
# 3. 定义加载项参数
prefs = {'profile.default_content_settings.popups': 0,
         'download.default_directory': 'f:\\'}
 
# 4.将加载项参数添加到谷歌浏览器加载项对象中
options.add_experimental_option('prefs', prefs)
 
# 5. 创建浏览器对象,并添加加载项对象
driver = webdriver.Chrome(options=options)
 
# 6. 方位下载页面
driver.get('https://npm.taobao.org/mirrors/chromedriver/80.0.3987.106/')
 
# 7. 点击下载
driver.find_element_by_link_text("chromedriver_win32.zip").click()
sleep(3)
 
# 8.关闭浏览器
driver.quit()

Note:
Other common startup parameters of chrome
are directly added to the configuration information when needed.

  • Cancel the save path pop-up box when the browser downloads
"download.prompt_for_download": False,
"download.directory_upgrade": True,
    
"""
'profile.default_content_settings.popups': 0
是禁止弹出所有窗口
"""
  • Whether to prompt security warning
# 下载xml文件时,会弹出“此文件类型可能会损害您的计算机”的提示。
# 而不显示消息警告,需要添加下面配置,使用Selenium chromedriver禁用此弹出窗口。
"safebrowsing.enabled": True

 

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey, and I hope it can help you! Partners can click the small card below to receive  

Guess you like

Origin blog.csdn.net/okcross0/article/details/132427988