回答編集履歴

1

HTML全体の中から、特定のtagのみ削除(その子供は残す)するコード

2017/04/26 13:10

投稿

coba-coba
coba-coba

スコア1409

test CHANGED
@@ -35,3 +35,87 @@
35
35
  </img>
36
36
 
37
37
  ```
38
+
39
+
40
+
41
+ 追記
42
+
43
+ ---
44
+
45
+ HTML全体の中から、特定のtagのみ削除(その子供は残す)するコード。
46
+
47
+ ```Python
48
+
49
+ import bs4
50
+
51
+
52
+
53
+ html = """
54
+
55
+ <body>
56
+
57
+ <p>
58
+
59
+ <a href="http://hogehoge.com/fuga.jpg">
60
+
61
+ <img class="hogehoge" src="http://hoge.example.com/hoge.jpg">
62
+
63
+ </a>
64
+
65
+ </p>
66
+
67
+ <p>
68
+
69
+ <a href="http://hogehoge.com/fuga.jpg">
70
+
71
+ <img class="hogehoge" src="http://fuga.example.com/fuga.jpg">
72
+
73
+ </a>
74
+
75
+ </p>
76
+
77
+ </body>
78
+
79
+ """
80
+
81
+
82
+
83
+ soup = bs4.BeautifulSoup(html, "html.parser")
84
+
85
+
86
+
87
+ while (soup.a):
88
+
89
+ soup.a.unwrap()
90
+
91
+
92
+
93
+ print(soup.prettify())
94
+
95
+ ```
96
+
97
+ ```
98
+
99
+ # 出力
100
+
101
+ <body>
102
+
103
+ <p>
104
+
105
+ <img class="hogehoge" src="http://hoge.example.com/hoge.jpg">
106
+
107
+ </img>
108
+
109
+ </p>
110
+
111
+ <p>
112
+
113
+ <img class="hogehoge" src="http://fuga.example.com/fuga.jpg">
114
+
115
+ </img>
116
+
117
+ </p>
118
+
119
+ </body>
120
+
121
+ ```