[Python automated testing]: file upload and download

file upload

  • Call send_keys()method to upload file
  • send_keys()The usage scenario :
    • Upload files using inputtags andtype= file
  • Code:
# 定位元素
element = driver.find_element()
# 元素调用send_keys方法,传入参数为要上传文件的地址
element.send_keys()
  • 【Example】
# 导包
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep

# 定义一个浏览器对象
driver = webdriver.Chrome()

# 定位到图片上传元素
element = driver.find_element(By.XPATH, '//*[@id="app"]/div/section/section/main/div/div[2]/div[1]/div/div/div[4]/div[1]/div/div[2]/form/div[9]/div/div[1]/div[1]/div/input')
# 对定位到的元素调用send_keys()方法即可实现文件上传
# 地址的最前面加上一个字母“r”,可以使得反斜杠\不起到转义功能
element.send_keys(r'C:\Users\Olivia\Pictures\300-300\22.gif')

# 为方便看清楚上传效果,页面停留5秒钟
sleep(5)
# 退出浏览器
driver.quit()

file download

picture download

Implementation steps

  1. Open the page where the image exists
  2. Locate the image element on the page
  3. Use element.attribut('属性名')the method to get srcthe attribute value of the attribute, which is the storage address url of the image
  4. Call reqests.get(url)the method to obtain image data (image data is binary data); if the obtained data is binary, it is required reqests.get(url).content; if the obtained data is a file type, it is requiredreqests.get(url).text
  5. save the file locally

[Example]: Download the logo picture of Baidu homepage

# 导包
from selenium import webdriver
from selenium.webdriver.common.by import By
# 导入请求包
import requests

driver = webdriver.Chrome()
# 打开百度首页
driver.get('https:www.baidu.com')
# 定位到百度logo图片
logo_element = driver.find_element(By.ID, 's_lg_img')
# 获取该元素的src属性的值,也即要获取图片的存放地址
logo_url = logo_element.get_attribute('src')
# 请求图片存取地址获取图片数据
# response.txt获取文件数据;response.content获取二进制数据
datas = requests.get(logo_url).content

# 将图片内容保存到本地
# wb表示写入二进制文件
with open(r'E:\123\baidu.png', 'wb') as file:
    file.write(datas)

file download

example

# selenium文件下载
# 导包
import os
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By

# 实例化一个ChromeOptions类的对象
options = webdriver.ChromeOptions()

# 设置打开浏览器时需要添加的参数
param = {
    
    
    # 禁止浏览器弹出弹窗
    'profile.default_content_settings.popups': 0,
    # 设置浏览器默认下载路径
    # os.getcwd()获取当前路径
    'download.default_directory': os.getcwd()
}
# 给浏览器添加属性
options.add_experimental_option('prefs', param)
# 创建一个谷歌浏览器对象
driver = webdriver.Chrome(options=options)
# 打开要下载文件的页面
driver.get('https://pypi.org/project/selenium/#files')
# 定位到要下载的文件元素
element= driver.find_element(By.LINK_TEXT, 'selenium-4.8.2.tar.gz')
# 点击该元素进行下载操作
element.click()

sleep(3)
driver.quit()

Guess you like

Origin blog.csdn.net/Lucifer__hell/article/details/129725567