Selenium file Upload all methods finishing Summary

Source: Internet
Author: User

This article reproduces the original blog of "Grey Blue". http://blog.csdn.net/huilan_same/article/details/52439546

File upload is all UI Automation testing to face a headache problem, today bloggers here to share their own experience in handling documents upload, hoping to help the vast number of files uploaded to the pit Seleniumer.

First of all, we have to distinguish between the type of the Upload button, in general, can be divided into two, one is the input box, the other is more complex, through JS, Flash and other implementations, the label is not input

We analyze each of these two separately:

1.input Label

As we all know, the input tag can be directly send_keys, here is no exception, to see the code example:

Example URL: http://www.sahitest.com/demo/php/fileUpload.htm

Code:

# -*- coding: utf-8 -*-from selenium import webdriverdriver = webdriver.Firefox()driver.get(‘http://sahitest.com/demo/php/fileUpload.htm‘)upload = driver.find_element_by_id(‘file‘)upload.send_keys(‘d:\\baidu.py‘) # send_keysprint upload.get_attribute(‘value‘) # check valuedriver.quit()

Results:

baidu.py

Obviously, for input upload, direct Send_keys is the simplest solution.

2. Non-input upload

Next difficulty to upgrade, for those not input box implementation of the upload how to do, this upload strange, useful a tag, useful div, useful button, useful object, we have no way to deal with these uploads directly on the Web page, the only way is to open the OS bullet box, To handle the frame.

The problem comes again, the OS frame involved in the plane is not selenium can solve, how to do? Very simple, with OS-level operation to deal with Bai, here we basically found a way to deal with the problem.

There are generally the following solutions:

    1. AutoIT, with the help of external forces, we go to call its generated AU3 or EXE file.
    2. Python Pywin32 Library to identify dialog handles and manipulate
    3. SendKeys Library
    4. Keybd_event, similar to 3, but analog button, Ctrl+a,ctrl+c, Ctrl + V ...

At present, I only know the above four ways, there are other methods of please leave a message to tell me, let me learn a bit.

Let's look at it in turn:

1. AutoIT

About AutoIt uploading and parameterization I've already talked about it in another blog post, see the autoit command-line arguments for selenium . Don't repeat it here.

2.win32gui

Nonsense not to say, on the code first:

Example URL: http://www.sahitest.com/demo/php/fileUpload.htm

Code:

#-*-Coding:utf-8-*-From seleniumImport WebdriverImport Win32guiImport Win32conImport Timedr = Webdriver. Firefox () Dr.get (' http://sahitest.com/demo/php/fileUpload.htm ') upload = dr.find_element_by_id (' File ') Upload.click () Time.sleep (1)# Win32guidialog = Win32gui. FindWindow (' #32770 ',U ' File Upload ')# dialog box ComboBoxEx32 = Win32gui. FindWindowEx (Dialog,0,' ComboBoxEx32 ',None) ComboBox = Win32gui. FindWindowEx (ComboBoxEx32,0, ' ComboBox ', None) Edit = Win32gui. FindWindowEx (ComboBox, 0, ' Edit ', None) # The above three sentences look for the object until you find the handle to the input box Edit object button = Win32gui. FindWindowEx (Dialog, 0, ' button ', None) # OK button buttonwin32gui.sendmessage (Edit, Win32con. Wm_settext, None, ' d:\\baidu.py ') # Enter the absolute address Win32gui into the input box. SendMessage (Dialog, Win32con. WM_COMMAND, 1, Button) # press buttonprint upload.get_attribute (' value ') dr.quit ()   

Results:

baidu.py

Here you need a very important gadget: Spy + +, Baidu a lot of, of course, you can also use autoit own tools, but no this good, suggest go next.

And, you have to install the pywin32 Library, you can find the library corresponding to your Python version, note that 32-bit or 64-bit must match the version of Python you installed.

After installation, in the "Start Menu Python folder" See PyWin32 's document "Python for Windows Documentation", you can find the corresponding method API.

A brief introduction to several uses:

Win32gui. FindWindow (Lpclassname=none, Lpwindowname=none):

    • From the top-level window, start looking for the matching Criteria window and return the handle to the window.
    • Lpclassname: Class name, can be seen in Spy + +
    • Lpwindowname: Window name, name you can see on the title bar
    • In the code example we used to find the upload window, you can use only one of them, with classname positioning is easy to be disturbed by other things, with windowname positioning instability, different upload dialog may window_name different, how to locate depending on your situation.

Win32gui. FindWindowEx (hwndparent=0, hwndchildafter=0, Lpszclass=none, Lpszwindow=none)

    • Searches for a form that matches the class name and form name, and returns a handle to the form. Returns 0 if not found.
    • hWndParent: If not 0, the search handle is a subform of the hWndParent form.
    • Hwndchildafter: If not 0, the subform is searched backwards from the hwndchildafter in the order of Z-index, otherwise the search starts from the first subform.
    • Lpclassname: Character type, is the form's class name, this can be found in Spy + +.
    • Lpwindowname: The character type is the window name, which is the title you can see on the title bar.
    • In the code example we use layers to find the input box and find the OK button

Win32gui. SendMessage (HWnd, MSG, WParam, LParam)

    • HWnd: integral type, form handle for receiving messages
    • MSG: integer, message to be sent, these messages are pre-defined by Windows, see System Definition messages (system-defined Messages)
    • WParam: Integral type, message WParam parameter
    • LParam: Integral type, message LParam parameter
    • In the code example, we used to enter the file address into the input box and click the OK button

As for the Win32API module as well as other methods, there is no more description, want to know the self Baidu or see Pywin32 documents.

3.SendKeys

The first thing to install is the SendKeys library, which can be installed with PIP

Pip Install SendKeys

code example:

Example URL: http://www.sahitest.com/demo/php/fileUpload.htm

Code:

#-*-coding : Utf-8-*-from selenium import webdriverimport win32guiimport win32conimport Timedr = Webdriver. Firefox () dr.get ( ' http://sahitest.com/demo/php/fileUpload.htm ') upload = Dr.find_element _by_id ( ' file ') Upload.click () time.sleep (1) # Sendkeyssendkeys.sendkeys ( ' d:\\baidu.py ') # Send file Address Sendkeys.sendkeys (" {ENTER} ") # send Enter Span class= "Hljs-keyword" >print upload.get_attribute ( ' value ') dr.quit ()   

Results:

baidu.py

You can enter information directly into the focus through the SendKeys library, but be aware that the open window is slightly more waiting time, otherwise it is easy to send the first letter (or you can add a useless character to the address), but I think this method is very unstable, not recommended.

4.keybd_event

Win32API provides a keybd_event () method to simulate the button, but this method is more cumbersome, also unstable, so it is not recommended, the following gives some code examples, if you want to study, Baidu to learn it.

...# First find an input box, enter the address of the file you want to upload, cut to the Clipboard Video.send_keys (' C:\\users\\administrator\\pictures\\04b20919fc78baf41fc993fd8ee2c5c9.jpg ') Video.send_keys (Keys.CONTROL,' A ')# Selenium Send_keys (ctrl + A) Video.send_keys (Keys.control,' X ')# (CTRL+X) driver.find_element_by_id (' Uploadimage '). Click ()# Click the Upload button to open the Upload box# paste (Ctrl + V) win32api.keybd_event (17,0,0,0)# Press the key ctrlwin32api.keybd_event (86,0,0,0)# Press the button vwin32api.keybd_event (86, 0 , Win32con. Keyeventf_keyup, 0) # Rising button vwin32api.keybd_event (17, 0, Win32con. Keyeventf_keyup, 0) # Rising button Ctrltime.sleep ( 1) # Enter (enter) win32api.keybd_event (13, 0, 0, 0) # Press the button enterwin32api.keybd_event (13, 0, Win32con. Keyeventf_keyup, 0) # rising button Enter ... 

is not very troublesome, of course, you can even use the button to enter the entire path, but I think no one would like to do so. And in the process you can not move the mouse at will, can not use the Clipboard, too unstable, so it is not recommended that you use this method.

3. Multi-File Upload

Then there is another situation that deserves our consideration, that is, multiple file uploads. How to upload multiple files, of course, we still enter the file path in the input box, so the only thing to figure out is the multi-file upload, the file path is how to write.

Let me tell you, a multi-file upload is a single path in quotation marks in the File path box, and then separate multiple paths with commas, which is as simple as:
"D:\a.txt" "D:\b.txt"
However, it is important to note that there are only a few files in the same path that can be used, otherwise it will fail (the following notation is not possible):
"C:\a.txt" "D:\b.txt"

Then find an example to try:

Example URL: http://www.sucaijiayuan.com/api/demo.php?url=/demo/20150128-1

Code:

#-*-Coding:utf-8-*-From seleniumImport WebdriverImport Win32guiImport Win32conImport Timedr = Webdriver. Firefox () Dr.get (' Http://www.sucaijiayuan.com/api/demo.php?url=/demo/20150128-1 ') dr.switch_to.frame (' iframe ')# Be sure to pay attention to Framedr.find_element_by_class_name (' Filepicker '). Click () Time.sleep (1) Dialog = Win32gui. FindWindow (' #32770 ',None) 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 ',  None) # with the code of the above example is the same, but the parameters passed here are different, if willing to write an upload function to encapsulate the upload function Win32gui. SendMessage (Edit, Win32con. Wm_settext, 0, 1, button) print dr.find_element_by_id ( ' Status_info '). Textdr.quit ()          

Results:

选中3张文件,共1.17KB。

Can be seen, multi-file upload is not so complex, but also very simple, the only difference is that the input parameters are different. AutoIt can also be implemented, interested to try it yourself.

And we can find that the code above this window is the same as in the previous example, that we can extract the uploaded parts, write a function, so that each time to upload, directly to call the function, the parameters can be passed.

Selenium file Upload all methods finishing Summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.