Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Created October 18, 2017 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cartman0/4bc9da60396ab4deb5997b2fecabaa06 to your computer and use it in GitHub Desktop.
Save Cartman0/4bc9da60396ab4deb5997b2fecabaa06 to your computer and use it in GitHub Desktop.
はてなブログAPI 記事の編集
import requests
import bs4
hatena_id="<hatena_id>"
blog_id="<blog_id>"
password="<api_key>"
entry_id = "8599973812308945752"
member_uri = "https://blog.hatena.ne.jp/{hatena_id}/{blog_id}/atom/entry/{entry_id}".format(hatena_id=hatena_id, blog_id=blog_id,entry_id=entry_id)
res_member = requests.get(member_uri, auth=(hatena_id, password))
if not res_member.ok:
raise Exception("Failed: status_code: " + str(res_member.status_code))
soup_response_xml = bs4.BeautifulSoup(res_member.content, features="xml")
def create_xml(base_xml_soup,
title=None,
author=None,
updated=None,
categories=[],
draft=None,
content=None):
# XMLsoupのクローン
update_soup_xml = bs4.BeautifulSoup(str(base_xml_soup), features="xml")
# id 削除
if update_soup_xml.id: update_soup_xml.id.decompose()
# link 削除
for l in update_soup_xml.findAll("link"):
l.decompose()
# delete published
if update_soup_xml.published: update_soup_xml.published.decompose()
# delete app:edited
edited = update_soup_xml.find("app:edited")
if edited:
edited.decompose()
# delete summary
if update_soup_xml.summary: update_soup_xml.summary.decompose()
# delete formatted_content
formatted = update_soup_xml.find("formatted-content")
if formatted:formatted.decompose()
# title
if title: update_soup_xml.title.string = title
# author
if author: update_soup_xml.author.string = author
# updated
if updated: update_soup_xml.updated.string = updated
# category
for new_c in categories:
cate_tag = update_soup_xml.new_tag("category")
cate_tag.attrs = {"term": new_c}
update_soup_xml.append(cate_tag)
# draft: yes, no
if draft: soup_response_xml.find("app:draft").string = draft
# content書き換え
if content: update_soup_xml.content.string = content
return update_soup_xml
updata_souop_xml = create_xml(soup_response_xml, content="# content1")
requests.put(member_uri, data=str(update_soup_xml).encode("utf-8"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment