回答編集履歴
1
文字化け対策
answer
CHANGED
@@ -4,16 +4,18 @@
|
|
4
4
|
import lxml.html
|
5
5
|
import pandas as pd
|
6
6
|
|
7
|
-
df = pd.DataFrame({'
|
7
|
+
df = pd.DataFrame({'列1':[1,2], '列2':[3,4]}, index = ['index1','index2']) # 日本語を含む
|
8
8
|
df2 = df.to_html()
|
9
|
+
|
9
10
|
table = lxml.html.fromstring(df2)
|
10
11
|
|
11
12
|
# rootにdivを配置し、配下にtableとp(コメント)を配置
|
13
|
+
# 文字化けしないようにfromstringではunicode文字列で渡し、tostringではエンコーディングを指定する
|
12
|
-
root = lxml.html.fromstring(
|
14
|
+
root = lxml.html.fromstring(u'<div></div>')
|
13
15
|
root.append( table)
|
14
|
-
comment = lxml.html.fromstring('<p>
|
16
|
+
comment = lxml.html.fromstring(u'<p>コメント</p>')
|
15
17
|
root.append(comment)
|
16
|
-
html = lxml.html.tostring(root)
|
18
|
+
html = lxml.html.tostring(root,encoding='utf-8')
|
17
19
|
print(html)
|
18
20
|
```
|
19
21
|
結果
|
@@ -22,8 +24,8 @@
|
|
22
24
|
<thead>
|
23
25
|
<tr style="text-align: right;">
|
24
26
|
<th></th>
|
25
|
-
<th>
|
27
|
+
<th>列1</th>
|
26
|
-
<th>
|
28
|
+
<th>列2</th>
|
27
29
|
</tr>
|
28
30
|
</thead>
|
29
31
|
<tbody>
|
@@ -38,7 +40,7 @@
|
|
38
40
|
<td>4</td>
|
39
41
|
</tr>
|
40
42
|
</tbody>
|
41
|
-
</table><p>
|
43
|
+
</table><p>コメント</p></div>
|
42
44
|
```
|
43
45
|
詳細は以下などが参考になります。
|
44
46
|
[lxmlでhtmlを処理する](http://www.cafe-gentle.jp/challenge/tips/python_tips_001.html#2)
|