Python 简明教程

Python - Automation Tutorial

Automation using Python

使用 Python 进行自动化涉及使用编程技术自动执行任务,通常不需要人工干预。Python 提供了各种库,使其成为自动化不同类型重复性任务的一个强大工具,包括任务调度、网页抓取、GUI 自动化以及更多。

Automation with Python involves using programming techniques to perform tasks automatically, typically without human intervention. Python provides various libraries to make it a powerful tool for automating different types of repetitive tasks including, task scheduling, web scraping, GUI automation and many more.

通过利用 Python 的大量库,可以创建适用于特定需求的自动化解决方案。

Utilizing the Python’s extensive libraries, can create automation solutions to fit specific needs.

Python Libraries for Automation

以下是通常用于自动化的几个 Python 库:

Following are the few of the Python libraries that are commonly used for automation −

  1. unittest − Unit testing framework in Python.

  2. Selenium − Web automation framework for testing web applications across different browsers.

  3. Beautiful Soup − Library for parsing HTML and XML documents, used for web scraping.

  4. pandas − Data manipulation library, useful for automating data analysis tasks.

  5. requests − HTTP library for sending HTTP requests and handling responses.

  6. Selenium − A web automation framework for testing web applications across different browsers.

  7. PyAutoGUI − GUI automation library for simulating mouse and keyboard actions.

在本教程中,您将了解使用 Python 进行自动化的各个方面,包括使用 schedule 模块进行任务调度、使用 BeautifulSoup 进行网页抓取,以及使用 BeautifulSoup 进行 GUI 自动化。

In this tutorial you will learn about the various aspects of automation using Python, from scheduling tasks with schedule module, web scraping with BeautifulSoup, and GUI automation with BeautifulSoup.

此处我们提供了实际示例,请确保在使用以下命令在命令提示符中执行本地系统中的提供的代码之前,安装了必要的模块:

Here we are providing practical examples and please ensure that you have the necessary modules installed before executing the provided codes in your local system using the below commands in your command prompt −

pip install schedule
pip install beautifulsoup4
pip install pyautogui

Python Automation with "schedule" Module

Python 中的 schedule 模块允许安排任务在指定的时间间隔或时间自动运行。它是自动化重复性任务(比如作业调度、定期任务或基于时间事件)的理想选择。

The schedule module in Python allows scheduling tasks to run automatically at specified intervals or times. It’s ideal for automating repetitive tasks such as job scheduling, periodic tasks, or time-based events.

Example

此示例演示了使用 Python 的 schedule 模块自动化日常任务(比如安排每周会议、设置闹钟等)的应用。

This example demonstrates the application of Python for automating routine tasks such as scheduling weekly meetings, setting alarms, and more, using Python’s schedule module.

import schedule
import time

# Function definitions for scheduled tasks
def alarm():
   print("Time to restart the server   ")

def job():
   print("Starting daily tasks   ")

def meet():
   print('Weekly standup meeting   ')

# Schedule tasks
schedule.every(5).seconds.do(alarm)  # Run every 5 seconds
schedule.every().day.at("10:30").do(job)  # Run daily at 10:30 AM
schedule.every().monday.at("12:15").do(meet)  # Run every Monday at 12:15 PM

# Main loop to execute scheduled tasks
while True:
   schedule.run_pending()
   time.sleep(0.5)

输出

Output

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

Time to restart the server
Time to restart the server
Time to restart the server
...

Python Web Scraping

网络抓取是自动化任务的一个简单示例。它是个从网站自动提取信息的过程。此项技术涉及提取网页并从 HTML 内容中提取所需数据。

Web scraping is a straightforward example of automation task. It is a process of automatically extracting information from websites. This technique involves fetching web pages and extracting the required data from the HTML content.

网络抓取广泛用于数据挖掘、数据分析和必需从网络收集信息的自动化任务。

Web scraping is widely used for data mining, data analysis, and automated tasks where collecting information from the web is necessary.

Example

此示例演示了如何使用 BeautifulSoupurllib.request 模块抓取含有关键字“python”的 URL 的网页。

This example demonstrates how to use BeautifulSoup and the urllib.request module to scrape a webpage for URLs containing the keyword "python".

from bs4 import BeautifulSoup
from urllib.request import urlopen
import re

html = urlopen("https://www.tutorialspoint.com/python/index.htm")
content = html.read()
soup = BeautifulSoup(content, "html.parser")
for a in soup.findAll('a',href=True):
   if re.findall('python', a['href']):
      print("Python URL:", a['href'])

Output

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

Python URL: /machine_learning_with_python/index.htm
Python URL: /python_pandas/index.htm
Python URL: /python/index.htm
Python URL: /python/index.htm
Python URL: /python_pandas/index.htm
Python URL: /python_pillow/index.htm
Python URL: /machine_learning_with_python/index.htm
Python URL: /python_technologies_tutorials.htm
Python URL: /python/index.htm
....

Automating Mouse Movements with "pyautogui"

pyautogui 模块允许 Python 脚本自动化鼠标移动、键盘输入和窗口交互,这对于测试 GUI 应用程序或自动化重复的桌面任务非常有用。

The pyautogui module allows your Python scripts to automate mouse movements, keyboard inputs, and window interactions, useful for testing GUI applications or automating repetitive desktop tasks.

Example

此示例演示了如何使用 Python 的 pyautogui 模块在方格图案中自动化鼠标移动。

This example demonstrates how the Python’s pyautogui module can be used to automate mouse movements in a square pattern.

import pyautogui

# Move the mouse in a larger square pattern
for i in range(5):
   pyautogui.moveTo(300, 100, duration=0.25)
   pyautogui.move(300, 0, duration=0.25)
   pyautogui.move(0, 300, duration=0.25)
   pyautogui.move(-300, 0, duration=0.25)
   pyautogui.move(0, -300, duration=0.25)

Output

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

python automation

Automating Unit Testing in Python

Python 中的 unittest 模块用于自动化测试。自动化单元测试是为诸如函数或方法之类的代码各个单元编写测试,并自动运行这些测试以确保它们的行为符合预期。

The unittest module in Python is used for automated testing. Automated unit testing is the practice of writing tests for individual units of code, such as functions or methods, and running these tests automatically to ensure they behave as expected.

Python 中的 unittest 模块是提供用于创建并运行自动化测试的框架的内置库。

The unittest module in Python is a built-in library that provides a framework for creating and running automated tests.

Example

此示例演示了如何在 Python 中使用 unittest 模块对字符串方法执行自动化测试。每个测试用例方法都以前缀 unittest 开始,它被 test_ 框架识别为要运行的方法。

This example demonstrates how to use the unittest module in Python to perform automated testing on string methods. Each test case method begins with the prefix test_, which is recognized by the unittest framework as a method to run.

# importing unittest module
import unittest

class TestingStringMethods(unittest.TestCase):
   # string equal
   def test_string_equality(self):
      # if both arguments are then it's succes
      self.assertEqual('ttp' * 5, 'ttpttpttpttpttp')

   # comparing the two strings
   def test_string_case(self):
      # if both arguments are then it's succes
      self.assertEqual('Tutorialspoint'.upper(), 'TUTORIALSPOINT')

   # checking whether a string is upper or not
   def test_is_string_upper(self):
      # used to check whether the statement is True or False
      self.assertTrue('TUTORIALSPOINT'.isupper())
      self.assertFalse('TUTORIALSpoint'.isupper())

   def test_string_startswith(self):
       # Used the startswith() to identify the start of the string
       self.assertTrue('tutorialspoint'.startswith('putor'))
       self.assertFalse('tutorialspoint'.startswith('point'))

# running the tests
unittest.main(verbosity=2)

Output

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

test_is_string_upper (__main__.TestingStringMethods) ... ok
test_string_case (__main__.TestingStringMethods) ... ok
test_string_equality (__main__.TestingStringMethods) ... ok
test_string_startswith (__main__.TestingStringMethods) ... FAIL

======================================================================
FAIL: test_string_startswith (__main__.TestingStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "main.py", line 23, in test_string_startswith
    self.assertTrue('tutorialspoint'.startswith('putor'))
AssertionError: False is not true

----------------------------------------------------------------------
Ran 4 tests in 0.000s

FAILED (failures=1)