Python web automated testing - file upload

There are three ways to upload files:

(1) Check the element tag. If it is input, you can upload the file by referring to the text box input form.

Method: Same as user input, use send_keys

1

2

3

4

5

步骤:1、找到定位元素,2,输入文件路径

ele=driver.find_element_by_id("id")

#说明:参数是文件的路径,在windows中,因为路径是反斜杠,所以在路径之前需要有r

ele.send_keys(r"c:\xxx.txt")

time.sleep(3)


Note: If it is not an input tag, but directly a div tag, you cannot use the above method, nor can you use the (drag and drop method) drag_and_drop(value1, value2) in selenium, because the files in the folder are window operations, not browsers. The element in cannot be located. Then use the following method:

(2) Use pywinauto (can only be used on the window platform)

Steps: 1. Download the pywinauto package------pip install pywinauto

Step 2: import from pywinauto .keyboard import send_keys

Step 3: Open the window >>> Enter the file address >>> Click the Open button. Please see the specific code.

The specific code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import pywinauto

from pywinauto.keyboard import send_keys

# 使用pywinauto来选择文件

app = pywinauto.Desktop()

# 选择文件上传的窗口

dlg = app["打开"]

# 选择文件地址输入框,点击激活

dlg["Toolbar3"].click()

# 键盘输入上传文件的路径>>>记住不是文件的地址啊,是文件的上一层地址.

send_keys("D:\data")

# 键盘输入回车,打开该路径

send_keys("{VK_RETURN}")

# 选中文件名输入框,输入文件名>>>只需要改文件名就行了,看以下例子

dlg["文件名(&N):Edit"].type_keys("文件名")<br>

# 例如我实战的:

dlg["文件名(&N):Edit"].type_keys("接口测试文件.pdf")<br>

# 点击打开

dlg["打开(&O)"].click()

time.sleep(4)

(3) If the computer is not a window operating system - use pyautogui cross-platform

1

使用pyautogui跨平台

1

2

3

4

5

6

7

8

9

10

11

12

13

pip install pillow==6.2.2

pip insall pyautogui

time.sleep(1)

pyautogui.write("d:xxx.txt")

pyautogui.press("enter",2)#输入两次enter键,防止出错

# 说明,有的平台,文件路径中如果包含中文,会报错,解决办法:

import pyperclip    #pyautogui中自带的,因此不需要单独安装

pyperclip.copy(r"d:\用户\文件.txt")#复制文件路径

time.sleep(2)

pyautogui.hotkey("ctrl","v")#类似于剪切板上面的粘贴操作

pyautogui.press("enter",presses=2)#输入两次enter键,防止出错

Finally, I would like to thank everyone who read my article carefully. Looking at the increase in fans and attention, there is always some courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly!

Software Testing Interview Document

We must study to find a high-paying job. The following interview questions are from the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.
 

Insert image description here

Guess you like

Origin blog.csdn.net/myh919/article/details/132761827