如何使用 Python 和 Wordpress REST API 获取所有 Wordpress 帖子为 JSON

在我们之前的文章如何使用 Python 和 WordPress REST API 获取 WordPress 帖子为 JSON中,我们展示了如何使用 Python 中的 Wordpress REST API 获取单页 10 篇帖子

在本文中,我们将使用分页来获取所有帖子的列表。

首先,我们观察到一旦我们查询无效页面如 ?page=1000000,返回的 JSON 将是

wp_posts_error.json
{'code': 'rest_post_invalid_page_number',
 'message': 'The page number requested is larger than the number of pages available.',
 'data': {'status': 400}}

而不是代表帖子列表的 JSON 数组。

使用此信息,我们可以编写一个获取器,每次获取 100 篇帖子的页面,直到遇到此错误消息:

fetch_all_posts.py
from tqdm import tqdm
import requests

def page_numbers():
    """无限生成页码"""
    num = 1
    while True:
        yield num
        num += 1

posts = []
for page in tqdm(page_numbers()):
    # 获取下一页 [pagesize=10] 帖子
    posts_page = requests.get("https://mydomain.com/wp-json/wp/v2/posts", params={"page": page, "per_page": 100}).json()
    # 检查"最后一页"错误代码
    if isinstance(posts_page, dict) and posts_page["code"] == "rest_post_invalid_page_number": # Found last page
        break
    # 无错误代码 -> 添加帖子
    posts += posts_page

Check out similar posts by category: Python, Wordpress