PythonでBeautifulSoupを使ってスクレイピング処理。
Json形式でデータをファイルに出力しようとしたところで以下のエラー。
File "hoge.py", line 227, in <module>
json.dump(nParagraphdic, expfile, indent=4, ensure_ascii=False)
File "/anaconda3/lib/python3.7/json/__init__.py", line 179, in dump
for chunk in iterable:
File "/anaconda3/lib/python3.7/json/encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "/anaconda3/lib/python3.7/json/encoder.py", line 405, in _iterencode_dict
yield from chunks
File "/anaconda3/lib/python3.7/json/encoder.py", line 438, in _iterencode
o = _default(o)
File "/anaconda3/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Tag is not JSON serializable
実施した対処
「TypeError: Object of type Tag is not JSON serializable」でググる。
以下の回答にたどり着く。

TypeError: Object of type 'Tag' is not JSON serializable
I am trying to create a JSON object and send it to the Firebase Database using python, but when I do this I get: TypeErr...
回答の以下箇所を確認。
HTMLそのままJSONにしたかったので、それができないっぽい。
Being a
bs4.element.Tag,addresscan not be serialised to JSON.How you handle this depends on what part of the tag you want to store in your db. If you just call
str()on theTagthe output will include the XML/HTML markup. If you want the text contained within the tag, access the.textattribute e.g.
さてどう処理したものか。としばらく思案したものの良い考えは出ず、
結局は上記回答の通りにする。
HTMLそのままを書き込みたかったけどやめて、
「.text」メソッドを使って格納したところ問題なく出力できるようになった。
とりあえずこれで先にすすめる。


コメント