python+selenium——实现文件上传

文件上传是web页面上很常见的一个功能一般分两个场景:

一、一种是input标签,这种可以用selenium提供的send_keys()方法轻松解决

二、另外一种是非input标签实现起来比较困难,可以借助autoit工具或者SendKeys第三方库。

    1 Autolt 需要去调用其生成的.au3或.exe文件.----不推荐,了解
    2 SendKeys第三方库(目前只支持到2.7版本)----不推荐,了解
    3 Python pywin32库,识别对话框句柄,进而操作 ------pip install pywin32

首先来看第一种input标签——这种有一个很明显的标识:它是一个input标签,并且type属性的值为file,如下图红色框框

from selenium import webdriver
driver=webdriver.Chrome()
driver.get("http://test.api2.danglaoshi.net:3001/course/list")
driver.add_cookie({"name":"sid","value":"s%3AaZDRAZT2cT-U83UIXOPjoEDFa3oGd57B.UtMLs9VnZuyr8EAH38h9ymRK45bI%2BINUk%2Fz59N8H8mM"})
driver.get("http://test.api2.danglaoshi.net:3001/course/list")

driver.find_element_by_xpath("//button[@onclick=\"window.location.href='/course/addCourse'\"]").click()
driver.find_element_by_xpath("//input[@id=\"courseThumbnailInput\"]").send_keys(r"C:\Users\TTT\Desktop\2028.jpg_wh300.jpg")
driver.find_element_by_xpath("//*[@id=\"addCourseForm\"]/div/div[1]/div/div/div/div[1]/div/div[1]/div[2]/div[2]/a").click()
View Code

猜你喜欢

转载自www.cnblogs.com/yhms/p/10895620.html
今日推荐