python基础(高级)

字典 (dict)

字典是一种键值对的数据结构,非常适合用于存储和检索数据。

python 复制代码
# 创建字典:
person = {"name": "Alice", "age": 25, "city": "New York"}
# 访问字典元素:
print(person["name"])  # 输出: Alice
print(person.get("name"))  # 输出: Alice
# 添加和修改元素:
person["email"] = "alice@example.com"  
# 添加新元素
person["age"] = 26  # 修改现有元素
# 删除元素:
del person["city"]  # 删除元素
# 遍历字典:
for key, value in person.items():  
  print(f"{key}: {value}")

集合 (set)

集合是一种无序且不重复的数据结构,非常适合用于去重和集合操作。

python 复制代码
# 创建集合:numbers = {1, 2, 3, 4}
# 添加和删除元素:
numbers.add(5)  # 添加元素
numbers.remove(3)  # 删除元素
# 集合操作:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2  # 并集
intersection = set1 & set2  # 交集
difference = set1 - set2  # 差集
symmetric_difference = set1 ^ set2  # 对称差集

文件和目录操作

在自动化测试中,文件和目录操作是必不可少的一部分。Python 提供了多种方法来处理文件和目录。

文件路径操作

python 复制代码
# 导入 os 模块:import os
# 获取当前工作目录:
current_dir = os.getcwd()print(current_dir)
# 改变工作目录:
os.chdir("/path/to/new/directory")
# 创建目录:
os.mkdir("/path/to/new/directory")
# 删除目录:
os.rmdir("/path/to/directory")
# 列出目录内容:
files = os.listdir("/path/to/directory")print(files)
python 复制代码
# 路径拼接:
path = os.path.join("/home/user", "data", "file.txt")print(path)
# 检查文件或目录是否存在:
if os.path.exists("/path/to/file.txt"):    
    print("File exists")
else:    
    print("File does not exist")
# 获取文件大小:
size = os.path.getsize("/path/to/file.txt")print(size)

正则表达式

正则表达式是处理字符串的强大工具,特别是在解析和匹配文本时非常有用。

python 复制代码
# 导入 re 模块
import re
# 基本匹配# 匹配字符串:
pattern = r"\d+"  # 匹配一个或多个数字
text = "The price is 100 dollars."
match = re.search(pattern, text)
if match:    
    print(match.group())  # 输出: 100
# 替换字符串:
new_text = re.sub(r"\d+", "XXX", text)
print(new_text)  # 输出: The price is XXX dollars.
# 查找所有匹配项:
matches = re.findall(r"\d+", text)
print(matches)  # 输出: ['100']

日志记录

在编写自动化测试脚本时,日志记录是非常重要的,可以帮助你追踪程序运行过程中的信息和错误。

python 复制代码
# 导入 logging 模块
import logging# 设置日志级别# 基本配置:
logging.basicConfig(level=logging.DEBUG,                   
format='%(asctime)s - %(levelname)s - %(message)s')# 记录日志:
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")
# 输出到文件# 配置日志文件:
logging.basicConfig(filename='app.log', level=logging.DEBUG,                    format='%(asctime)s - %(levelname)s - %(message)s')

单元测试

单元测试是验证代码正确性的关键步骤。Python 提供了 unittest 模块来简化单元测试的编写和执行。

# 导入 unittest 模块

import unittest``# 编写测试用例``# 定义测试类:

class TestAddition(unittest.TestCase):``

def test_add(self):

self.assertEqual(add(1, 2), 3)

def test_add_negative(self):

self.assertEqual(add(-1, -2), -3)

if __name__ == '__main__':

unittest.main()# 定义测试函数:

def add(a, b):``

return a + b

性能分析

性能分析可以帮助你找出程序中的瓶颈,并优化代码。Python 提供了 cProfile 模块来进行性能分析。

导入 cProfile 模块

复制代码
import cProfile分析函数使用 cProfile 分析函数:def example_function():    # Your code here    passcProfile.run('example_function()')

第三方库

Python 社区提供了大量的第三方库,可以极大地扩展 Python 的功能。下面是一些常用的第三方库。

安装第三方库

复制代码
使用 pip 安装库:pip install requestspip install beautifulsoup4

使用第三方库

复制代码
# 使用 requests 库发送 HTTP 请求:import requestsresponse = requests.get("https://api.example.com/data")print(response.status_code)print(response.json())# 使用 beautifulsoup4 解析 HTML:from bs4 import BeautifulSoupimport requestsresponse = requests.get("https://www.example.com")soup = BeautifulSoup(response.text, 'html.parser')print(soup.title.string)
相关推荐
Sapphire~2 分钟前
【前端基础】04-XSS(跨站脚本攻击,Cross-Site Scripting)
前端·xss
奔跑的web.3 分钟前
Vue 3.6 重磅新特性:Vapor Mode 深度解析
前端·javascript·vue.js
MediaTea4 分钟前
Python OOP 设计思想 13:封装服务于演化
linux·服务器·前端·数据库·python
love530love5 分钟前
突破 ComfyUI 环境枷锁:RTX 3090 强行开启 comfy-kitchen 官方全后端加速库实战
人工智能·windows·python·cuda·comfyui·triton·comfy-kitchen
爱敲代码的婷婷婷.5 分钟前
patch-package 修改 node_modules流程以及注意点
前端·react native·前端框架·node.js
极客先躯5 分钟前
高级java每日一道面试题-2025年5月09日-基础篇[协议-注解-缓存]-JCache(JSR-107)是什么?它的主要目标是什么?
java·spring·缓存
u0104058366 分钟前
Java应用的链路追踪:实现分布式跟踪
java·开发语言·分布式
wang6021252186 分钟前
流式输出注意点
python·状态模式·fastapi
未定义.2218 分钟前
第3篇:UI自动化核心操作:输入、点击、弹窗、下拉框全场景实战
运维·python·ui·自动化·jenkins·集成测试·pytest
这是个栗子9 分钟前
【API封装参数传递】params 与 API 封装
开发语言·前端·javascript·data·params