diff --git a/script.py b/script.py new file mode 100644 index 0000000..0baa1a4 --- /dev/null +++ b/script.py @@ -0,0 +1,96 @@ +import requests +import json +from time import sleep +from requests.auth import HTTPBasicAuth + +BASE_URL = "https://livetse.ir/wp-json/wp/v2/comments" + +USERNAME = "your_username" +APP_PASSWORD = "your_application_password" + + +def fetch_comments(post_id=None, per_page=100): + all_comments = [] + page = 1 + total_pages = 1 + + while page <= total_pages: + params = { + "per_page": per_page, + "page": page, + "status": "approve" + } + + if post_id: + params["post"] = post_id + + try: + response = requests.get( + BASE_URL, + params=params, + auth=HTTPBasicAuth(USERNAME, APP_PASSWORD), + timeout=10 + ) + + if response.status_code == 200: + comments = response.json() + + if page == 1: + total_pages = int(response.headers.get("X-WP-TotalPages", 1)) + print(f"Total pages: {total_pages}") + + if not comments: + print("No more comments.") + break + + all_comments.extend(comments) + print(f"Fetched page {page}/{total_pages} ({len(comments)} comments)") + + page += 1 + sleep(0.5) + + elif response.status_code == 401: + print("Authentication failed ") + break + + elif response.status_code == 403: + print("Access forbidden ") + break + + elif response.status_code == 400: + print("Bad request :", response.text) + break + + else: + print(f"Error: {response.status_code} - {response.text}") + break + + except requests.exceptions.RequestException as e: + print("Request failed:", e) + break + + return all_comments + + +def save_to_json(data, filename="comments.json"): + with open(filename, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + + +def main(): + post_id = None + + comments = fetch_comments(post_id=post_id) + + print(f"\nTotal comments fetched: {len(comments)}") + + for c in comments[:3]: + print("-" * 40) + print("Author:", c.get("author_name")) + print("Content:", c.get("content", {}).get("rendered")) + + save_to_json(comments) + + +if __name__ == "__main__": + main() \ No newline at end of file