LoginSignup
14
10

More than 5 years have passed since last update.

lxml使って、htmlファイルを書き換える

Posted at

やりたかったこと

base.html内のタグの中に、insert.htmlの内容を挿入した結果を、output.htmlとして書き出したかった。

今回は、pythonのlxmlモジュール使ってみた。

ベースファイル(base.html)

base.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>テスト</title>
  <xml id="toolbox"></xml>
</head>
<body>

</body>
</html>

挿入内容(insert.html)

insert.html

<category id="hoge">
    <block></block>
</category>

出力結果(output.html)

output.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>テスト</title>
  <xml id="toolbox">
    <category id="hoge">
        <block></block>
    </category>
  </xml>
</head>
<body>

</body>
</html>

スクリプト(joint.py)

下記のスクリプトで、イメージどおりのoutput.htmlが生成される。

joint.py
import lxml.html

def unescape(s):
  s = s.replace("&lt;", "<")
  s = s.replace("&gt;", ">")
  # this has to be last:
  s = s.replace("&amp;", "&")
  return s

def readContent(path):
  f = open(path)
  content = f.read()
  f.close()
  return content

base_path = "./"

insert = base_path + "insert.html"
base = base_path + "base.html"
output = base_path + "index.html"
id = 'toolbox'

html = readContent(base)
html = html.decode('utf-8')
root = lxml.html.fromstring(html)

element = root.get_element_by_id(id)
html = readContent(insert)

element.text = html
content = lxml.html.tostring(root,encoding="utf-8")
text =  unescape(content)

f = open(output,"w")
f.write(text)
f.close()

備考

lxmlのインストール

lxmlモジュールは、pipで一発。

pip install lxml

htmlタグの置換

タグのテキストは、そのままでは<> が、 &lt;&gt; になってるので、下記関数で置換した。

def unescape(s):
  s = s.replace("&lt;", "<")
  s = s.replace("&gt;", ">")
  # this has to be last:
  s = s.replace("&amp;", "&")
  return s

文字化け対策

ファイル内の日本語が文字化けしていたので、下記コードでデコードとエンコードした。

#読み込み
html = html.decode('utf-8')

#書き込み
content = lxml.html.tostring(root,encoding="utf-8")
14
10
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
10