English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python+Example of Selenium Auto-Clicking After Logging in to an Account

The company limits the time to view the code during codereview, in fact, many codes are automatically generated by the framework and do not require much time to view. In order to meet the standard, some time needs to be brushed (mouse clicks on a fixed area of the web page). I think it can be completed by using the means of automated testing to complete this kind of invalid physical labor.

First, clarify the requirements:   

  1. automatically open web pages   
  2. login account 
  3. click on a fixed area at regular intervals

The two solutions I think of are sikuli or python+selenium. The advantage of sikuli is that the logical operation is simple and direct, using images as identifiers, the disadvantage is that the window needs to be fixed, and it cannot run in the background. Selenium is slightly more complex, but runs fast, and the window can be obscured.

Here is a simple record of using Python+a small example of selenium.

using Python version3.3and selenium2, Windows environment (now supporting3version 0.0 and above, many forums and blogs have not been updated).

First is the installation of the software, Python is not elaborated on, remember to set the environment variables.

Below is the installation of selenium, if pip has been installed. Run the command directly.

pip install -U selenium

Another way ishttps://pypi.python.org/packages/source/s/selenium/selenium-2.52.0.tar.gzDownload and unzip. Here is a brief description of the Windows version, actually it is more or less the same under Unix, use Wget to download and install.

使用命令(setup一般用于第三方模块的安装):

Use the command (setup is generally used for the installation of third-party modules):3cd c:\Python
\xxxx

python setup.py install

During the installation process, ImportError: No module named setuptools may occur, which is because the setuptools module is missing, and Python does not install it by default.http://pypi.python.org/pypi/setuptoolsThe above provides installation packages and instructions for installation for various systems. For Windows systems, downloadhttps://bootstrap.pypa.io/ez_setup.pyAutomated installation script.

Run:

python ez_setup.py

After completion, you can install selenium.

Here, I will give a simple explanation of the process with my own example.

The first step is to complete the opening of the browser.

selenium2Combined with selenium and webdriver, directly import the corresponding drivers of various browsers and open them. Note that the chrome driver may need to be installed separately.

from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://www.xxx.com')

After opening the web page, you need to log in, F12Open the browser debugger, use the small arrow to select the element, and view the properties of the login box account and password. Generally, there is an ID. Selenium can obtain elements through the following methods and perform various operations. For specific explanations, please refer to the link document above:

  1. find_element_by_id
  2. find_element_by_name
  3. find_element_by_xpath
  4. find_element_by_link_text
  5. find_element_by_partial_link_text
  6. find_element_by_tag_name
  7. find_element_by_class_name
  8. find_element_by_css_selector

Among them, id is the most effective and convenient, and it should be considered first. After selecting the element, you can use the WebDriver API to call the simulated keyboard input and mouse click operations. The code is as follows:

username="qun" 
passwd="passwd"
browser = webdriver.Firefox()
browser.get('https://www.xxx.com')
browser.implicitly_wait(10)
elem=browser.find_element_by_id("loginFormUserName")
elem.send_keys(username)
elem=browser.find_element_by_id("loginFormPassword")
elem.send_keys(passwd)
elem=browser.find_element_by_id("loginFormSubmit")
elem.click()

After logging in, the page will usually jump to a new page. How to get the new page? Here is the concept of window handle, which is completed by switching the window handle. Note! Sometimes when an element is inside a frame, it also needs to be switched through swtich. The appearance of a wait function (as mentioned above) is because the page needs to load time, and the element may not be loaded out until after the click, which will be explained in detail in the next section.

browser.implicitly_wait(10)
browser.switch_to_window(browser.window_handles[-1")

After selecting the area to be clicked, here we use xpath to locate, because in the process of automated testing, elements may not be located by id, name and other methods (many people do not write them, love table nested table, I also have no way), and xpath comes into play. A common lazy method is to install xpath plugin in Firefox, right-click to obtain it directly. This is not introduced because it is not encouraged, using plugins will cause such things to充斥 in the code:   

XPath (/html/body/div/div[3]/div[2]/div[4]/p[2")

If possible, use the characteristics of elements to locate them, such as the name of a button.

Or locate child elements through parent elements.

username =browser.find_element_by_xpath("//input[@name='username']")
clear_button = browser.find_element_by_xpath("//form[@id='loginForm']/input[4")

The code is as follows, the usage of By that often appears on the internet requires importing the package.

from selenium.webdriver.common.by import By

Here is another function, I don't know what the difference is- -。

for i in range(100):
  elem=WebDriverWait(browser, 30).until(
    lambda x:x.find_element_by_xpath("//table[@class='aaa']"/td[1))
  elem.click()
  time.sleep(20)
  print ("click",i)

Then here we also need to mention the wait function in selenium2There are two types of waiting: explicit waiting and implicit waiting.  

Explicit Waiting

Explicit waiting is to explicitly wait for the appearance of a certain element or certain conditions such as clickability, and keep waiting until it is found, unless an exception is thrown because the element is not found within the specified time.

element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "myDynamicElement"))
  )

Implicit Waiting

Note that implicit waiting is to inform that all DOM elements should wait for a certain amount of time when searching for an element, if not found immediately, try again for this amount of time.

browser.implicitly_wait(10) # seconds

The difference between the two is that one is to manage the timeout object directly, and the other is to entrust it to the webdriver.

Of course, you can also wait passively by using the sleep method. Remember to import the time package.

time.sleep(20)

This is just a simple demonstration of the usage, there are many places that can be improved, no functions are encapsulated, and no multithreading is used to concurrently execute multiple routines. Improvements will be made as needed in the future.

That's all for this article, I hope it will be helpful to everyone's learning, and I also hope everyone will support the Naya Tutorial.

Declaration: The content of this article is from the network, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been edited by humans, nor does it assume any relevant legal liability. If you find content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (when sending an email, please replace # with @ to report, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like