本指南介紹如何在使用 NewsDataHub API 時對結果進行分頁。
NewsDataHub API 是一項透過 RESTful API 介面提供新聞資料的服務。它實現基於遊標的分頁以有效處理大型資料集,允許開發人員以可管理的批次檢索新聞文章。每個回應都包含一組文章,其中每個文章物件包含標題、描述、發布日期、來源、內容、關鍵字、主題和情緒分析等詳細資訊。此 API 使用遊標參數在結果中進行無縫導航,並為搜尋參數和過濾選項等高級功能提供全面的文件。
有關文檔,請造訪:https://newsdatahub.com/docs
API 通常在其回應中傳回有限數量的數據,因為在單一請求中傳回所有結果通常是不切實際的。相反,他們使用分頁——一種將數據分成單獨的頁面或批次的技術。這允許客戶端一次檢索一頁,存取結果的可管理子集。
當您向 /news 端點發出初始請求並收到第一批結果時,回應的形狀如下所示:
{ "next_cursor": "VW93MzoqpzM0MzgzMQpqwDAwMDQ5LjA6MzA0NTM0Mjk1T0xHag==", "total_results": 910310, "per_page": 10, "data": [ { "id": "4927167e-93f3-45d2-9c53-f1b8cdf2888f", "title": "Jail time for wage theft: New laws start January", "source_title": "Dynamic Business", "source_link": "https://dynamicbusiness.com", "article_link": "https://dynamicbusiness.com/topics/news/jail-time-for-wage-theft-new-laws-start-january.html", "keywords": [ "wage theft", "criminalisation of wage theft", "Australian businesses", "payroll errors", "underpayment laws" ], "topics": [ "law", "employment", "economy" ], "description": "Starting January 2025, deliberate wage theft will come with serious consequences for employers in Australia.", "pub_date": "2024-12-17T07:15:00", "creator": null, "content": "The criminalisation of wage theft from January 2025 will be a wake-up call for all Australian businesses. While deliberate underpayment has rightly drawn scrutiny, our research reveals that accidental payroll errors are alarmingly common, affecting nearly 60% of companies in the past two years. Matt Loop, VP and Head of Asia at Rippling Starting January 1, 2025, Australias workplace compliance landscape will change dramatically. Employers who deliberately underpay employees could face fines as high as AU. 25 million or up to 10 years in prison under new amendments to the Fair Work Act 2009 likely. Employers must act decisively to ensure compliance, as ignorance or unintentional errors wont shield them from civil or criminal consequences. Matt Loop, VP and Head of Asia at Rippling, says: The criminalisation of wage theft from January 2025 will be a wake-up call for all Australian businesses. While deliberate underpayment has rightly drawn scrutiny, our research reveals that accidental payroll errors are alarmingly common, affecting nearly 60% of companies in the past two years. Adding to the challenge, many SMEs still rely on fragmented, siloed systems to manage payroll. This not only complicates operations but significantly increases the risk of errors heightening the potential for non-compliance under the new laws. The urgency for businesses to modernise their approach cannot be overstated. Technology offers a practical solution, helping to streamline and automate processes, reduce human error, and ensure compliance. But this is about more than just avoiding penalties. Accurate and timely pay builds trust with employees, strengthens workplace morale, and fosters accountability. The message is clear: wage theft isnt just a financial risk anymoreits a criminal offense. Now is the time to ensure your business complies with Australias new workplace laws. Keep up to date with our stories on LinkedIn, Twitter, Facebook and Instagram.", "media_url": "https://backend.dynamicbusiness.com/wp-content/uploads/2024/12/db-3-4.jpg", "media_type": "image/jpeg", "media_description": null, "media_credit": null, "media_thumbnail": null, "language": "en", "sentiment": { "pos": 0.083, "neg": 0.12, "neu": 0.796 } }, // more article objects ] }
注意 JSON 回應中的第一個屬性 - next_cursor。 next_cursor 中的值指向下一頁結果的開頭。當發出下一個請求時,您可以像這樣指定遊標查詢參數:
https://api.newsdatahub.com/v1/news?cursor=VW93MzoqpzM0MzgzMQpqwDAwMDQ5LjA6MzA0NTM0Mjk1T0xHag==
嘗試對結果進行分頁的最簡單方法是透過 Postman 或類似工具。這是一個簡短的視頻,演示瞭如何使用遊標值在 Postman 中對結果進行分頁。
https://youtu.be/G7kkTwCPtCE
當 next_cursor 值為 null 時,表示您已到達所選條件的可用結果的結尾。
使用 Python 對結果進行分頁
以下是如何使用 Python 透過 NewsDataHub API 結果設定基本分頁。
import requests # Make sure to keep your API keys secure # Use environment variables instead of hardcoding API_KEY = 'your_api_key' BASE_URL = 'https://api.newsdatahub.com/v1/news' headers = { 'X-Api-Key': API_KEY, 'Accept': 'application/json', 'User-Agent': 'Mozilla/5.0 Chrome/83.0.4103.97 Safari/537.36' } params = {} cursor = None # Limit to 5 pages to avoid rate limiting while demonstrating pagination for _ in range(5): params['cursor'] = cursor try: response = requests.get(BASE_URL, headers=headers, params=params) response.raise_for_status() data = response.json() except (requests.HTTPError, ValueError) as e: print(f"There was an error when making the request: {e}") continue cursor = data.get('next_cursor') for article in data.get('data', []): print(article['title']) if cursor is None: print("No more results") break
基於索引的分頁
有些 API 使用基於索引的分頁將結果分割成離散的區塊。透過這種方法,API 會傳回特定的資料頁,類似於書中的目錄,其中每個頁碼都指向特定的部分。
雖然基於索引的分頁實作起來更簡單,但它有幾個缺點。它難以即時更新,可能會產生不一致的結果,並且會給資料庫帶來更大的壓力,因為檢索每個新頁面需要順序掃描先前的記錄。
我們已經介紹了 NewsDataHub API 中基於遊標的分頁的基礎知識。有關搜尋參數和過濾選項等進階功能,請參閱完整的 API 文件:https://newsdatahub.com/docs。
以上是使用 NewsDataHub API 了解分頁的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python的靈活性體現在多範式支持和動態類型系統,易用性則源於語法簡潔和豐富的標準庫。 1.靈活性:支持面向對象、函數式和過程式編程,動態類型系統提高開發效率。 2.易用性:語法接近自然語言,標準庫涵蓋廣泛功能,簡化開發過程。

Python因其簡潔與強大而備受青睞,適用於從初學者到高級開發者的各種需求。其多功能性體現在:1)易學易用,語法簡單;2)豐富的庫和框架,如NumPy、Pandas等;3)跨平台支持,可在多種操作系統上運行;4)適合腳本和自動化任務,提升工作效率。

可以,在每天花費兩個小時的時間內學會Python。 1.制定合理的學習計劃,2.選擇合適的學習資源,3.通過實踐鞏固所學知識,這些步驟能幫助你在短時間內掌握Python。

Python適合快速開發和數據處理,而C 適合高性能和底層控制。 1)Python易用,語法簡潔,適用於數據科學和Web開發。 2)C 性能高,控制精確,常用於遊戲和系統編程。

學習Python所需時間因人而異,主要受之前的編程經驗、學習動機、學習資源和方法及學習節奏的影響。設定現實的學習目標並通過實踐項目學習效果最佳。

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

禪工作室 13.0.1
強大的PHP整合開發環境

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

WebStorm Mac版
好用的JavaScript開發工具