はてなキーワード: decoderとは
import requests import json from urllib.parse import quote def fetch_bookmarks(url): try: # URLをエスケープ escaped_url = quote(url, safe="") api_url = f"https://b.hatena.ne.jp/entry/json/?url={escaped_url}" response = requests.get(api_url) response.raise_for_status() try: return response.json() except json.decoder.JSONDecodeError as e: print(f"Error decoding JSON from {api_url}: {e}") print("Response content:", response.text) return [] except requests.exceptions.RequestException as e: print(f"Error fetching bookmarks from {api_url}: {e}") return [] def find_common_bookmarks(bookmarks1, bookmarks2, url1, url2): common_users = set(bm["user"] for bm in bookmarks1 if bm["comment"]) & set(bm["user"] for bm in bookmarks2 if bm["comment"]) common_bookmarks = [] for user in common_users: comments = [] for bm in bookmarks1: if bm["user"] == user and bm["comment"]: comments.append({"url": url1, "comment": bm["comment"], "timestamp": bm["timestamp"]}) break for bm in bookmarks2: if bm["user"] == user and bm["comment"]: comments.append({"url": url2, "comment": bm["comment"], "timestamp": bm["timestamp"]}) break if len(comments) == 2: common_bookmarks.append({"user": user, "comments": comments}) return common_bookmarks if __name__ == "__main__": url1 = "https://news.yahoo.co.jp/articles/f9966c4ccc374fc88babbb50175a9ea844c99638" url2 = "https://www.asahi.com/articles/ASN6K7F64N6KUJHB00L.html" data1 = fetch_bookmarks(url1) data2 = fetch_bookmarks(url2) common_bookmarks = find_common_bookmarks(data1["bookmarks"], data2["bookmarks"], url1, url2) print(json.dumps(common_bookmarks, indent=2, ensure_ascii=False))
url1, url2のところを対象としたいものに変えれば使えるよ
バグあったら直して使ってね