selenium 实现上传图片/文件多种方法

前端之家收集整理的这篇文章主要介绍了selenium 实现上传图片/文件多种方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

个人在写脚本时遇到需要selenium来上传图片

第一种方法

一般比较简单的网站可以使用以下方法(只使用非常简单的网站):

browser.find_element_by_id("IdOfInputTypeFile").send_keys(os.getcwd()+"/image.png")

browser.find_element_by_xpath("IdOfInputTypeFile").send_keys(os.getcwd()+"/image.png")

第二种方法 使用pyautogui或者是autoit

import autoit

autoit.win_active("Open")
autoit.control_send("Open","Edit1",r"C:\Users\uu\Desktop\TestUpload.txt")
autoit.control_send("Open","{ENTER}")

# 建议使用control_set_text 因为control_send会发送错误的文本
autoit.control_set_text("Open",r"C:\Users\uu\Desktop\TestUpload.txt")

或者是

import autoit
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

ActionChains(driver).move_to_element( driver.find_element_by_xpath("//path/to/upload/button")).click().perform()
handle = "[CLASS:#32770; TITLE:Open]"
autoit.win_wait(handle, 60)
autoit.control_set_text(handle, "Edit1", "\\file\\path")
autoit.control_click(handle, "Button1")


第三种方法 使用pywin32

import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")   
shell.Sendkeys("C:\text.txt")  
shell.Sendkeys("~")

第二和第三种方法都有一点小问题时,就是当电脑在被使用时,会影响实际操作的结果。

原文:https://stackoverflow.com/questions/8665072/how-to-upload-file-picture-with-selenium-python

猜你在找的Python相关文章