はてなブログはapiを公開しており、そちらを使って更新したいと思います。
参考URL
cartman0.hatenablog.com
参考にしたサイトをほぼ丸パクリしています。
違う点は
* 関数にしている所
* 更新用の配列を渡している所
仕様
- はてなblogに必要なパラメータをセットする
- リプレース用の配列を渡す
- 更新用の関数を起動する
- urlからXMLをダウンロードする
- 必要な箇所を更新してXMLを作成する
- はてなブログAPIで更新する
ソース
import requests
import bs4
def update_blog(hatena_id:str , password:str , blog_id:str, entry_id:str,replace_data):
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)
print(member_uri)
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")
update_soup_xml = bs4.BeautifulSoup(str(soup_response_xml), features="xml")
if update_soup_xml.id: update_soup_xml.id.decompose()
for l in update_soup_xml.findAll("link"):
l.decompose()
if update_soup_xml.published: update_soup_xml.published.decompose()
edited = update_soup_xml.find("app:edited")
if edited:
edited.decompose()
if update_soup_xml.summary: update_soup_xml.summary.decompose()
hatena_formatted_content = update_soup_xml.find("hatena:formatted-content")
if hatena_formatted_content:
hatena_formatted_content.decompose()
new_author = ""
if new_author: update_soup_xml.author.string = new_author
new_updated = ""
if new_updated: update_soup_xml.updated.string = new_updated
new_categories = []
for new_c in new_categories:
cate_tag = update_soup_xml.new_tag("category")
cate_tag.attrs = {"term": new_c}
update_soup_xml.append(cate_tag)
new_draft = ""
if new_draft: soup_response_xml.find("app:draft").string = new_draft
new_content = update_soup_xml.content.string
for item in replace_data:
print(item[0] ,item[1] )
new_content =new_content.replace(item[0], item[1])
update_soup_xml.content.string = new_content
print( str(update_soup_xml.prettify()))
result_xml = requests.put(member_uri , auth=(hatena_id, password) , data=str(update_soup_xml).encode("utf-8"))
print(result_xml)
print(result_xml.text)
hatena_id = "masalib"
password = "xxxxxxx"
blog_id = "masalib.hatenablog.jp"
entry_id = "10328537792364688871"
replace_data = []
replace_data.append(["http://cdn-ak.f.st-hatena.com/images/fotolife/m/masalib/20160218/20160218144707.jpg","replace_url_1"] )
replace_data.append(["https://cdn-ak.f.st-hatena.com/images/fotolife/m/masalib/20190323/20190323161133.jpg","replace_url_2"] )
update_blog(hatena_id , password , blog_id, entry_id,replace_data)
結果
ステータスが200になった。
更新もできるようになった。これで次のステップにいける
はまった事
Blog_idがメインとサブが間違えていた
その場合に、データは取得できるけど、更新ができないという沼にはまった
エラー文言
The entry is not article of the blog" api
GETは成功するけど、PUTは失敗するという状態
GETでも失敗してほしかった