PAMIE-Python implements IE automation module (with NetEase registration code)

Source: Internet
Author: User

PAMIE is a set of tools written for Python for automated Web testing. It is implemented using Win32COM to operate IE.
Pamie is a good IE Operation Module
It is convenient to use pamie to operate IE browsers. Originally, it was an item for IE testing automation,
In this way, it is easy to use pamie to capture webpages and submit forms automatically.

Usage:
To test a simple example:

From cPAMIE import PAMIE

Ie = PAMIE ()

Ie. navigate ("google.com ")
Ie. textBoxSet ('Q', 'python ')
Ie. buttonClick ('btng ')
Ie. linkClick ('python Programming Language -- Official website ')
Ie. windowChange ('python Programming Language -- Official website ')
Ie. windowFind ('python Programming Language -- Official website ')
Ie. textBoxSet ('Q', "Automation ")
Ie. buttonClick ('submit ')

Directly operate the form element on the page and access the text information of the page to determine whether the user login is successful.

In pamie, how does one deal with the pop-up dialog box of Chinese titles?
Http://www.python-forum.org/pythonforum/viewtopic.php? F = 17 & t = 3194

Http://markmail.org/message/u3ojkyj2ns7p3dn3#query:+page:1+mid:5wuwfctervph6tlv+state:results

Python:

Import cPAMIE, cModalPopUp, winGuiAuto
Import time

Ie = cPAMIE. PAMIE ()
Wga = winGuiAuto

# Logon
Ie. navigate ('d: // python // WebDialogTest // 1.html ')

# Start a new process and automatically click "cancel"
ClickCancel = cModalPopUp. handlePopup ("Confirm", "cancel ")
ClickCancel. popupName = "select file"
ClickCancel. start ()

Ie. buttonClick ("install ")
Time. sleep (1)

ClickCancel. join () # process ended

Certificate -------------------------------------------------------------------------------------------------------------------------------------

Another introduction:

PAMIE
Is a very interesting module. It is a module for implementing IE automation. Previously, I used the ClientCookie module, which can use urllib2 to access pages through programs.
And is suitable for environments that require cookie support. However, some web access processes are not just like downloading files, but sometimes a system action. PAMIE should be a more
It is intuitive and easier to simulate the manual input process. However, the limitation is that it only supports IE, which can be used in some special cases.

To use it, you need to install the win32all module.

Below is its readme
A simple example is provided:

Import cPAMIE

Ie = cPAMIE. PAMIE ()

# Start Script:

Ie. Navigate ('HTTP: // pamie.sourceforge.net/pamieform.html ')
Ie. SetTextBox ('john', 'firstname', 0)
Ie. SetTextBox ('doe ', 'lastname', 0)
Ie. SetTextBox ('2014 State Street ', 'addline1', 0)
Ie. SetTextBox ('suite # 16', 'addline2', 0)
Ie. SetTextBox ('san Mateo ', 'city', 0)
Ie. SetListBox ('CA', 'state', 0)
Ie. SetTextBox ('20140901', 'zip', 0)

Ie. ClickButton ('submit ', 0)

That
After we download this module, it is a zip package. It is not in the installation mode. You can copy cPAMIE. py to the lib subdirectory under the python installation directory.
The above code is very simple. Pilot the cPAMIE module and generate an Automation Object ie. At this time, we will see that the program automatically opens an ie window, and our operations can be seen in this ie window
To display the executed part in yellow.

Ie. Navigate () is used to access a link.
Ie. SetTextBox () is used to set the value of a text field. The first parameter is the Input value, and the second parameter is the name of the Input field of the corresponding form table (you need to check the source code ), the third is the form name (in this example, 0 indicates the subscript ).
Ie. SetListBox () is used to set the value of the list box.
Ie. ClickButton () is used to simulate clicking a button. The first parameter is the button name, and the second parameter is 0 to indicate the subscript.

Some other available methods, such as ClickLink (), are written on the PAMIE homepage (). Its first parameter is the text corresponding to the link. If it is Chinese, convert it to unicode. For example, if the page is GB2312, the source code of the link is:

<A href = "http://xxx.com"> Chinese characters </a>

The call is as follows:

Ie. ClickButton (unicode ('kanji ', 'cp936 '))

This is not required in actual operation, as long as the parameter is unicode encoding.

If you view the source code, you can also see some other methods:

Quit () -- disable open ie
GoBack () -- back
Refresh () -- Refresh

If you are interested, you can give it a try. You can see the results on one side of the operation, which is very simple and convenient.

Bytes -------------------------------------------------------------------------------------------------------------------------------

Article 3

Python is simple and clear, and modules or component modules provided by third parties are also simple and clear.

The following is an example listing more comprehensive code and annotations...

#-*-Coding: cp936 -*-
Import sys

# I put all the files in pamie2.0 such as cPAMIE in the folder named pamie in the following path and added sys. path to facilitate the import of all the modules in the pamie folder.
# As long as CPAMIE can be imported, the example here can be run.
Sys. path. append (r "F:/Python25/lib/site-packages/pamie ")
Import cPAMIE

# New instance
Ie = cPAMIE. PAMIE ()

# Open the target webpage

Ie. navigate ('HTTP: // pamie.sourceforge.net/pamieform.html ')

# Note that the first parameter listed below, such as fistname, is the input name = "firstname" in the source code of the webpage"
# You cannot use the italics displayed on the webpage: "First Name :"
# Text box
Ie. textBoxSet ('firstname', 'justthisname ')

Ie. textBoxSet ('lastname', 'iamhere ')

# Select the drop-down menu:

Ie. listBoxSelect ('state', "MS ")

# Square selection box:

Ie. checkBoxSet ('cxbx ', 1) #1 2 3 or * are all "checked" meaning ''Null String indicates unselected

# Circle selection box: the names of these elements are easy to know when radio has been designed for Web pages.
# Select Jazz here
Ie. radioButtonSet ("music", "Jazz") # music is the name of the selection list. Find it from the source code of the webpage.

# Final submit button

Print "now submit button, as long as you input the following sentence in the Python interpreter, submit"
# It is much easier for ie. buttonClick ("Submit") to replace mouse clicks

# Input type = "submit" name = "Submit" in the source code. Therefore, the first parameter is the value of name "Submit"
# Pamie is case-sensitive.

# Ie. buttonClick ("Submit ")

# IE has its own features. It seems that the use of pamie to open multiple webpages is added to the same IE process, not a webpage or a process.

''' Many web pages are complex, such as image buttons and javaScript buttons.
Use ie. buttonImageClick ("submitRegister ")

Some buttons will execute javascript to submit the content after clicking the mouse, for example, the content in the source code is:
<Input type = "image" src = "http://www.sit.com/member/images/register.gif
"Width =" 100 "height =" 54 "border =" 0"
OnClick = "javascript: submitMe ();
That is to say, when you click the image called register.gif, javascript: submitMe () will be executed to submit the page:

Ie. javaScriptExecute ("javascript: submitMe ()") to automatically submit pages. After you move these buttons to the lower left corner of IE, the corresponding

Javascript: theFunction () is easy to find...

It is also possible to execute a javascript function with parameters... ie. javaScriptExecute ("javascript: submitMe ('param ')")
You can also directly set the value of an element in a webpage:
For example, if document. Form. id. value = "string" is set in the webpage source file, the following statements can be directly modified:

Ie. javaScriptExecute ("javascript: document. Form. id. value = 'thevalueyouwant '")

In addition, pamie2.0 has a module for processing simple pop-up windows. The title of such windows is generally Microsoft Internet Explorer.

Import cModalPopUp

A = cModalPopUp. handlePopup ('Confirm', "OK") # "the second parameter is" OK ", indicating that the text on the button in the pop-up window is" OK"

:

Run:

A. run () can be used to click the "OK" button in the "pop-up window...
Multi-threaded programs can be used to process such windows with one thread. This will not affect the main program...

Another useful table filling tool for pamie: AiRoboForm.exe

 

 

After installing the IE Toolbar tool, you can click Save to Save the webpage table, and move the cursor
When "Baidu" is stopped for a moment, a sub-menu is displayed. Select "edit" to view all the names of the form on the page.
If you have worked hard to find so many "first Parameters", you do not need to find the text box or the name of the list box. You can see the names of all the boxes to be filled in the opened Editor.
"Name" is only displayed in "lower case", you need to check in the source file whether the first letter is in uppercase, etc. .. pamie is case sensitive
AiRoboForm is case insensitive...

Pamie2.0 also has the following limitations:

Below is a reference from http://yinxl.spaces.live.com/blog/cns! 4626e4f8c0bfc0bc! 172. entry
".

In April May 14, PAMIE was able to easily control a new IE window.
During this time, I was writing a WEB Test Program. According to ZV's recommendation, I implemented it using Python, because an open-source package of PAMIE is very useful for testing WEB pages. However
PAMIE finds that its findWindow function is very difficult to use, making it difficult for the test program to control the new IE window, such as HTML: <a href = "B .html"
Target = "_ blank"> link_content </a>, the new IE window opened by this link.
You can't find a proper solution by reading the PAMIE source code. I have modified the cPAMIE. py
The constructor of the PAMIE class. The modified constructor can find the IE window that has been found based on the input URL address. If no matching window is found, PAMIE creates a new window.
Open the URL. The Modified code is as follows: from win32com. client import Dispatch # The import Statement to be added #2006-5-10 Modified by YinXianglong to find a opened IE Window. BEGIN
Def _ init _ (self, url = None, isFind = False, timeOut = 300 ):
"The class instantiation code. When the object is instantiated you can
Pass a starting URL. If no URL is passed then about: blank, a blank
Page, is brought up.
Parameters:
[Url]-url to navigate to initially
[IsFind]-if isFind = True, find a opened IE Window whose LocationURL is equal to url
[TimeOut]-how many 100 mS increments to wait, 10 = 1sec, 100 = 10sec
Returns:
Nothing
"""

Self. showDebugging = True # Show debug print lines?
Self. colorHighlight = "# F6F7AD" # Set to None to turn off highlighting
Self. frameName = None # The current frame name or index. Nested frames are
# Supported in the format frame1.frame2. frame3
Self. formName = None # The current form name or index
Self. busyTuner = 1 # Number of consecutive checks to verify document is no longer busy. find_ OK _flag = False
If isFind and (url! = ''):
Clsid = '{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' # CLSID for ShellWindows
ShellWindows = Dispatch (clsid)
Url = url. lower ()
For I in range (ShellWindows. Count ):
If ShellWindows [I]. LocationURL. lower (). find (url)>-1:
Self. _ ie = ShellWindows [I]
Find_ OK _flag = True
If not find_ OK _flag:
Print "Can't Find the opened IE Window whose LocationURL is equal to url ."
Self. _ ie = DispatchEx ('internetexplorer. application ')
If url:
Self. _ ie. Navigate (url)
Else:
Self. _ ie. Navigate ('about: blank ')

Self. _ timeOut = timeOut
Self. _ ie. Visible = 1
Self. timer = datetime. datetime. now ()
#2006-5-10 Modified by YinXianglong to find a opened IE Window.
END Other codes are the same as those of PAMIE2.0.
The following is the test code: import yxlPAMIE ie = yxlPAMIE. PAMIE ("
Http: // 172.17.153.171/NewSys/default. aspx

") Print ie. pageGetText ()

The test result shows the enabled http: // 172.17.153.171/NewSys/default. aspx.

The HTML code of the window.

 

Appendix: Netease registration code

# Coding: gbk
Import cPAMIE
Import time
Import random
Username = ''. join (random. sample ('abcdefghijklmnopqrstuvwxyz0123456789 ', 8 ))
Password = '******'
Zhanghao = '|'. join ([username, password])
Ie = cPAMIE. PAMIE ()

# Open the target webpage

Ie. navigate ('HTTP: // reg.163.com/reg0.shtml ')

# Note that the first parameter listed below, such as fistname, is the input name = "firstname" in the source code of the webpage"
# You cannot use the italics displayed on the webpage: "First Name :"
# Text box
Ie. textBoxSet ('username', username)

Ie. textBoxSet ('Password ','*****')
Ie. textBoxSet ('cpassword ','*****')

# Select the drop-down menu:

Ie. listBoxSelect ('Question ', unicode ('My User-Defined question', 'cp936') # note that encoding conversion cp936 can be changed to GBK.
Ie. textBoxSet ('myquery', 'wodewentishishenme ')
Ie. textBoxSet ('answer', 'wodoubuxihuan ')
Ie. textBoxSet ('Year', '20140901 ')
Ie. listBoxSelect ('month', '6 ')
Ie. listBoxSelect ('day', '22 ')
# Square selection box:

# Ie. checkBoxSet ('cxk', 1) #1 2 3 or * are all "checked" meaning ''Null String indicates unselected

# Circle selection box: the names of these elements are easy to know when radio has been designed for Web pages.
# Select Jazz here
Ie. radioButtonSet ("gender", "1") # music is the name of the selection list, which is found in the source code of the webpage.

# Final submit button

Print "Enter the verification code and submit"
# Ie. buttonClick ("Submit") # It is much easier to replace mouse clicks

I = 0
While I <100:
Pass
I = I + 1
If True = ie. findText (unicode ('congratulation ', 'gbk ')):
Break

Fp = open('163zhanghao.txt ', 'A ')
Fp. write (zhanghao + '/N ')
Fp. close ()
Ie. quit ()

 

 

Loop Registration

# Coding: gbk
Import cPAMIE
Import time
Import random
Username = ''. join (random. sample ('abcdefghijklmnopqrstuvwxyz0123456789 ', 8 ))
Password = 'wokao1'
Zhanghao = '|'. join ([username, password])
I = 0
While I <1000:
Ie = cPAMIE. PAMIE ()
Ie. navigate ('https: // passport.baidu.com /? Reg ')
Ie. textBoxSet ('username', username)
Ie. textBoxSet ('loginpass ','*****')
Ie. textBoxSet ('verifypass ','*****')
Ie. radioButtonSet ("sex", "1 ")
Ie. textBoxSet ("email", username + '@ msn.cn ')
I = 0
While I <1000:
Pass
I = I + 1
If True = ie. findText (unicode ('congratulation ', 'gbk ')):
Break
Fp = open('163zhanghao.txt ', 'A ')
Fp. write (zhanghao + '/N ')
Fp. close ()
Ie. quit ()
I = I + 1

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.