使用 Python 实现自动化
Python 自动化涉及使用编程技术自动执行任务,通常无需人工干预。Python 提供了各种库,使其成为自动化不同类型重复任务的强大工具,包括任务调度、网络抓取、GUI 自动化等等。
利用 Python 的广泛库,可以创建满足特定需求的自动化解决方案。
用于自动化的 Python 库
以下是一些通常用于自动化的 Python 库 -
- unittest − Python 中的单元测试框架。
- Selenium - 用于跨不同浏览器测试 Web 应用程序的 Web 自动化框架。
- Beautiful Soup - 用于解析 HTML 和 XML 文档的库,用于 Web 抓取。
- pandas − 数据操作库,可用于自动化数据分析任务。
- requests - 用于发送 HTTP 请求和处理响应的 HTTP 库。
- Selenium - 一个 Web 自动化框架,用于跨不同浏览器测试 Web 应用程序。
- PyAutoGUI — 用于模拟鼠标和键盘操作的 GUI 自动化库。
在本教程中,您将了解使用 Python 实现自动化的各个方面,从使用计划模块安排任务、使用 BeautifulSoup 进行网络抓取以及使用 BeautifulSoup 进行 GUI 自动化。
在这里,我们提供了实际示例,请确保在命令提示符中使用以下命令在本地系统中执行提供的代码之前,您已经安装了必要的模块 -
pip install beautifulsoup4
pip install pyautogui
使用 “schedule” 模块实现 Python 自动化
Python 中的计划模块允许计划任务以指定的时间间隔或时间自动运行。它非常适合自动执行重复性任务,例如作业调度、周期性任务或基于时间的事件。
例此示例演示了 Python 在 Python 的 schedule 模块中自动执行日常任务(例如安排每周会议、设置闹钟等)的应用。
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)
输出
在执行上述代码时,我们将得到以下输出 -
Time to restart the server
Time to restart the server
...
Python 网页抓取
Web 抓取是自动化任务的一个简单示例。这是一个从网站自动提取信息的过程。该技术涉及获取网页并从 HTML 内容中提取所需的数据。
Web 抓取广泛用于需要从 Web 收集信息的数据挖掘、数据分析和自动化任务。
例此示例演示如何使用 BeautifulSoup 和 urllib.request 模块来抓取包含关键字 “python” 的 URL 的网页。
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
html = urlopen("https://www.qikepu.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'])
输出
在执行上述代码时,我们将得到以下输出 -
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
....
使用 “pyautogui” 自动移动鼠标
pyautogui 模块允许您的 Python 脚本自动执行鼠标移动、键盘输入和窗互,这对于测试 GUI 应用程序或自动执行重复的桌面任务非常有用。
例此示例演示了如何使用 Python 的 pyautogui 模块以方形模式自动移动鼠标。
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)
输出
在执行上述代码时,我们将得到以下输出 -
在 Python 中自动执行单元测试
Python 中的 unittest 模块用于自动化测试。自动单元测试是指为各个代码单元(如函数或方法)编写测试,并自动运行这些测试以确保它们按预期运行。
Python 中的 unittest 模块是一个内置库,它为创建和运行自动化测试提供了一个框架。
例此示例演示如何使用 Python 中的 unittest 模块对字符串方法执行自动测试。每个测试用例方法都以前缀 test_ 开头,unittest 框架将其识别为要运行的方法。
# 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('qikepu'.upper(), 'qikepu')
# 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('qikepu'.isupper())
self.assertFalse('qikepu'.isupper())
def test_string_startswith(self):
# Used the startswith() to identify the start of the string
self.assertTrue('qikepu'.startswith('putor'))
self.assertFalse('qikepu'.startswith('point'))
# running the tests
unittest.main(verbosity=2)
输出
在执行上述代码时,我们将得到以下输出 -
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('qikepu'.startswith('putor'))
AssertionError: False is not true
----------------------------------------------------------------------
Ran 4 tests in 0.000s
FAILED (failures=1)