Python作为一门强大的编程语言,凭借其简洁易学的语法和丰富的生态系统,成为了众多开发者的首选。除了Python内置的标准库外,还有大量的第三方模块可以扩展Python的功能。在本篇博客中,我们将介绍一些工作中经常用到的一些偏工具类的第三方模块,它们能够帮助我们更高效地进行开发和解决各种问题。
一、jsonpath模块
jsonpath模块为我们提供了这样一种功能:通过表达式来提取一个json中某些节点的值
关于jsonpath的表达式,可以参考官网:JSONPath - XPath for JSON
下面列举一些常见的表达式
import json, jsonpath
content = '''
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
'''
obj = json.loads(content)
# 取所有书的作者
authors = jsonpath.jsonpath(obj, "$.store.book[*].author")
print(authors)
# 取所有的作者
authors = jsonpath.jsonpath(obj, "$..author")
print(authors)
# 取store下所有的子节点
staff = jsonpath.jsonpath(obj, "$.store.*")
print(staff)
# 取store下所有的价格,包括书、自行车的价格
prices = jsonpath.jsonpath(obj, "$.store..price")
print(prices)
# 取第一本书的价格
first_book = jsonpath.jsonpath(obj, "$..book[0]")
print(first_book)
# 最后一本书
last_book = jsonpath.jsonpath(obj, "$..book[(@.length-1)]")
print(last_book)
# 前两本书
first_two_books = jsonpath.jsonpath(obj, "$..book[0,1]")
print(first_two_books)
# 前两本书的另一种取值方法
first_two_books = jsonpath.jsonpath(obj, "$..book[:2]")
print(first_two_books)
# 所有书中有isbn属性的节点
books_contains_isbn = jsonpath.jsonpath(obj, "$..book[?(@.isbn)]")
print(books_contains_isbn)
# 价格小于10的书
books_low_price = jsonpath.jsonpath(obj, "$..book[?(@.price<10)]")
print(books_low_price)
# 作者是Nigel Rees的书
books_nigel_rees = jsonpath.jsonpath(obj, "$..book[?(@.author=='Nigel Rees')]")
print(books_nigel_rees)
二、requests模块
requests模块为我们提供了一种简单而优雅的方式来发送HTTP请求并处理响应。使用它可以发送GET和POST请求、处理响应内容,从而使我们的HTTP请求变得高效和可靠。
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
wd = {"wd": "谦谦君子,温润如玉"}
url = "https://www.baidu.com/s?"
# 支持get/post等http方法,可以设置参数、headers、cookies
response = requests.get(url, params=wd, headers=headers)
print(type(response))
# http响应码
print(response.status_code)
# 取出响应的unicode编码的字符串
data = response.text
print(data)
# 取出响应的二进制流,可以自己编码
binary_data = response.content
# 将响应内容解析为JSON格式
json_response = response.json()
三、tqdm模块
如果需要执行一个比较久的循环,那么我们希望可以看到执行进度,tqdm为我们提供了进度条的功能,下面是两种常见的使用方式。
from tqdm.autonotebook import tqdm
import time
# 第一种是将一个可迭代对象放入tqdm中
for i in tqdm(range(1, 5), colour="blue"):
time.sleep(1)
# 第二种是设置一个总量,然后在循环中手动更新
progress = tqdm(total=5, colour="blue")
for i in range(1, 5):
progress.update(1)
time.sleep(1)