Python Selenium File Upload method rollup _python

Source: Internet
Author: User
Tags sleep

File upload is all the UI Automation test to face a headache problem, today, bloggers here to share their own processing file upload experience, hope to be able to help the vast number of files to be uploaded pit Seleniumer.

First of all, we want to distinguish the type of upload button, can be divided into two types, one is the input box, the other is more complex, through JS, Flash and so on, the label is not input

We analyze each of these two:

1.input Label

As we all know, input tags can be directly send_keys, here is no exception, to see code examples:

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

Code:

#-*-Coding:utf-8-*-from
Selenium import webdriver

driver = 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_keys
print upload.get_attribute (' value ') # Check value

Driver.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 who are not input box implementation upload how to do, this upload strange, useful a label, useful div, useful button, useful object, we have no way through directly on the Web page to dispose of these uploads, the only way is to open the OS bomb box, To handle the frame.

The problem again, the OS bullet frame involved in the level is not selenium can be solved, how to do? Very simple, with OS level operation to deal with Bai, here we basically found the problem of processing methods.

In general, there are several solutions:
1.autoIT, with the help of external force, we go to call its generated AU3 or EXE file.
2.Python pywin32 Library, identify dialog box handles, and then operate
3.SendKeys Library
4.keybd_event, like 3, is just an analog button, Ctrl+a,ctrl+c, Ctrl + V ...

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

Let's look at this in turn:

1. AutoIt

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

2.win32gui

Nonsense not much to say, on the code first:

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

Code:

#-*-Coding:utf-8-*-from selenium import webdriver import Win32gui import
win32con

Import Time Dr = Webdriver. Firefox ()
dr.get (' http://sahitest.com/demo/php/fileUpload.htm ')
upload = dr.find_element_by_id (' file ')
Upload.click ()
time.sleep (1)

# Win32gui
dialog = Win32gui. FindWindow (' #32770 ', u ' file Upload ') # dialog
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 button = Win32gui of the input box Edit object
. FindWindowEx (dialog, 0, ' button ', None) # OK button

Win32gui. SendMessage (Edit, Win32con. Wm_settext, None, ' d:\\baidu.py ') # Enter an absolute address Win32gui to the input box
. SendMessage (Dialog, Win32con. WM_COMMAND, 1, button) # press button

print upload.get_attribute (' value ')
dr.quit ()

Results:

baidu.py

Here you need a very important gadget: Spy + +, Baidu has a lot of, of course, you can also use AutoIt with the tool, but no this good, suggest to the next bar.

Also, you have to install Pywin32 's library, where you can find a library that corresponds to your Python version, and note that 32-bit or 64-bit must correspond to the Python version you have installed.

You can find the corresponding method API from the PyWin32 document "Python for Windows Documentation" in the "Start Menu Python folder" After the installation is complete.

A brief introduction to several uses:

Win32gui. FindWindow (Lpclassname=none, Lpwindowname=none):
• A window that starts looking for matching criteria from the top window and returns the handle to the window.
Lpclassname: Class name, in Spy + + can see
lpwindowname: Window name, name of the title bar can see
• Code example we used to find the upload window, you can only use one of them, with classname positioning is easily disturbed by other things, with windowname positioning instability, different upload dialog box may window_name different, how to locate depending on your situation.

Win32gui. FindWindowEx (hwndparent=0, hwndchildafter=0, Lpszclass=none, Lpszwindow=none)
• Search for a form that matches the class name and form name and return the handle to the form. Return 0 if not found.
hwndparent: If not 0, the search handle is a subform of the hWndParent form.
Hwndchildafter: If not 0, search for the subform from Hwndchildafter backwards in z-index order, or start the search 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 receiving message
msg: integer, the message to send, these messages are all predefined by Windows, see System Definition messages (system-defined Messages)
wparam: Integral type, wParam parameter of message
lparam: Integral type, lParam parameter of message
• In the code example we use to enter the file address to the input box and click the OK button

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

3.SendKeys

To install the SendKeys library first, you can install it with PIP

Pip Install SendKeys

code example:

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

Code:

#-*-Coding:utf-8-*-from selenium import webdriver import Win32gui import
win32con

Import Time Dr = Webdriver. Firefox ()
dr.get (' http://sahitest.com/demo/php/fileUpload.htm ')
upload = dr.find_element_by_id (' file ')
Upload.click ()
time.sleep (1)

# SendKeys
sendkeys.sendkeys (' d:\\baidu.py ') # Send file Address
Sendkeys.sendkeys ("{ENTER}") # Send enter key

print Upload.get_attribute (' value ')
dr.quit ()

Results:

baidu.py

The SendKeys library allows you to enter information directly into the focus, but note that the open window is a little bit of wait time, otherwise it is easy to send the first letter (or you can add a useless character before the address), but I think this method is very unstable, not recommended.

4.keybd_event

Win32API provides a keybd_event () method to simulate the key, but this method is more cumbersome and 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 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 the Upload button to open the Upload box

# paste (Ctrl + V)
win32api.keybd_event (17, 0, 0, 0) # Press the key CTRL
Win32api.keybd_event (86, 0, 0, 0) # Press the button v
w In32api.keybd_event (0, Win32con.) Keyeventf_keyup, 0) # Raise the button v
win32api.keybd_event (0, Win32con). Keyeventf_keyup, 0) # Rising button Ctrl
Time.sleep (1)

# Enter (enter)
win32api.keybd_event (13, 0, 0, 0) # Press the button enter
   win32api.keybd_event (0, Win32con. Keyeventf_keyup, 0) # Raise the key to enter ...



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

3. Multi-File Upload

Then there is another situation that we should consider, that is, multiple file uploads. How to upload multiple files, of course, we still enter the file path to the input box, so the only thing to figure out is how the file path is written when multiple files are uploaded.

I'll tell you what, multiple-file uploads are a simple way to enclose a single path in quotes in a file path box and then separate multiple paths with commas, such as:
"D:\a.txt" "D:\b.txt"
But note that only multiple files in the same path can be used in this way, otherwise it will fail (the following wording is not possible):
"C:\a.txt" "D:\b.txt"

Then find an example to try:

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

Code:

#-*-Coding:utf-8-*-from selenium import webdriver import Win32gui import
win32con

Import Time Dr = 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 frame
dr.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)

# is the same as the code above, except that the parameters passed here are different, if you want to write an upload function to encapsulate the upload function
Win32gui. SendMessage (Edit, Win32con. Wm_settext, 0, ' d:\\baidu.py ' "d:\\upload.py" "d:\\1.html" "
Win32gui. SendMessage (Dialog, Win32con. WM_COMMAND, 1, button)


print dr.find_element_by_id (' Status_info '). Text
dr.quit ()

Results:

3 files selected, Total 1.17KB.

Visible, multiple file upload is not so complex, but also very simple, the only difference is the input parameters are different. AutoIt can also be realized, you are interested to try.

And we can see that the above window code is the same as in the previous example, that we can pull out the part of the upload, write a function, so that each time to upload, directly to call the function, passed the parameters.

Look, uploading is really good deal.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.