栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

selenium中的上传操作

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

selenium中的上传操作

input标签类型

如果是input,可以直接输入路径,那么我们就直接调用send_keys输入路径。
比如163邮箱写信时的添加附件功能,就是input标签:

实现代码:

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


driver = webdriver.Chrome()
driver.maximize_window()
driver.get("http://mail.163.com")

# 等待登录frame加载到dom树中,切换
login_form_loc = (By.XPATH, '//div[@id="loginDiv"]/iframe')
WebDriverWait(driver, 30).until(EC.frame_to_be_available_and_switch_to_it(login_form_loc))  # frame_to_be_available_and_switch_to_it这个方法是等待frame可用并切换至此frame


# 定位账户按钮,并输入内容
driver.find_element_by_xpath('//input[@name="email"]').send_keys("163账户")

# 定位密码框,并输入内容
driver.find_element_by_xpath('//input[@name="password"]').send_keys("密码")

# 定位登录按钮并点击
driver.find_element_by_xpath('//a[@id="dologin"]').click()

# 切换至默认frame
driver.switch_to.default_content()

# 等待写信按钮可见
write_button = (By.XPATH, '//ul/li[2]/span[@]')
WebDriverWait(driver, 30).until(EC.visibility_of_element_located(write_button))

# 定位写信按钮,并点击
driver.find_element(*write_button).click()

# 等待上传附件元素加载到dom树中
# upload_file_loc = (By.XPATH, '//div[@]/div[1]/div/input')
upload_file_loc = (By.XPATH, '//div[contains(@title, "一次可发送")]/input')
WebDriverWait(driver, 30).until(EC.presence_of_element_located(upload_file_loc))

# 使用send_keys传入文件路径
driver.find_element(*upload_file_loc).send_keys("D:\文件文档\os.docx")
非input标签类型

非input标签类型,需要借助第三方工具。
下面是使用pywin32(安装:pip install pywin32)封装好的上传类,只要出现Windows上传窗口后,直接调用就可以了:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/10/10 16:19
# @Author : admin
# @File : sel_lesson_upload.py
# @Software: PyCharm

import win32gui
import win32con

"""
1.找到输入框和打开按钮
2.输入地址,点击打开
"""


# 前提,Windows上传窗口已出现,sleep 2秒等待弹出的出现
def upload(filePath, browser_type="chrome"):
	browser_type = browser_type.lower()
    # 根据不同的浏览器,确认弹窗界面的title。
    if browser_type == "chrome":
        title = "打开"
    elif browser_type == "Edge":
        title = "打开"
    elif browser_type == "firefox":
        title = "文件上传"
    else:
        title = ""

    # 找元素
    # 找窗口 #32770, 打开
    dialog = win32gui.FindWindow("#32770", title)
    ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, "ComboBoxEx32", None)  # 二级
    comboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, "ComboBox", None)  # 三级
    # 编辑按钮
    edit = win32gui.FindWindowEx(comboBox, 0, 'Edit', None)  # 四级
    button = win32gui.FindWindowEx(dialog, 0, 'Button', "打开(&0)")  # 四级

    # 向编辑框中,输入文件路径
    win32gui.SendMessage(edit, win32con.WM_SETTEXT, None, filePath)
    win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button)

效果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/316001.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号