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")
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))
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()
driver.switch_to.default_content()
write_button = (By.XPATH, '//ul/li[2]/span[@class="oz0"]')
WebDriverWait(driver, 30).until(EC.visibility_of_element_located(write_button))
driver.find_element(*write_button).click()
upload_file_loc = (By.XPATH, '//div[contains(@title, "一次可发送")]/input')
WebDriverWait(driver, 30).until(EC.presence_of_element_located(upload_file_loc))
driver.find_element(*upload_file_loc).send_keys("D:\\文件文档\\os.docx")
非input标签类型
非input标签类型,需要借助第三方工具。 下面是使用pywin32(安装:pip install pywin32)封装好的上传类,只要出现Windows上传窗口后,直接调用就可以了:
import win32gui
import win32con
"""
1.找到输入框和打开按钮
2.输入地址,点击打开
"""
def upload(filePath, browser_type="chrome"):
browser_type = browser_type.lower()
if browser_type == "chrome":
title = "打开"
elif browser_type == "Edge":
title = "打开"
elif browser_type == "firefox":
title = "文件上传"
else:
title = ""
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)
效果:
|