質問するログイン新規登録

回答編集履歴

1

追記

2018/11/30 17:33

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -32,4 +32,30 @@
32
32
  **実行結果** [Wandbox](https://wandbox.org/permlink/Lg94H6qkEDk97XNv)
33
33
  ```
34
34
  <p>文字列1</p><div class="main"><h2 class="h2_main">文字列2文字列3文字列4</h2></div>
35
- ```
35
+ ```
36
+
37
+ 別解
38
+ ---
39
+ 正規表現に拘らないのであれば、こんな方法でも良いです。
40
+ ```Python
41
+ from bs4 import BeautifulSoup
42
+
43
+
44
+ text = '<p>文字列1</p><div class="main"><h2 class="h2_main"><p>文字列2</p>文字列3<em>文字列4</em></h2></div>'
45
+ soup = BeautifulSoup(text, 'html.parser')
46
+
47
+ h2 = soup.find('h2')
48
+ for e in h2.find_all():
49
+ e.unwrap()
50
+
51
+ print(soup)
52
+ ```
53
+
54
+ **実行結果**
55
+ ```
56
+ <p>文字列1</p><div class="main"><h2 class="h2_main">文字列2文字列3文字列4</h2></div>
57
+ ```
58
+
59
+ 実質三行で書けました。
60
+
61
+ 参考: [Beautiful Soup 4.2.0 Doc. 日本語訳](http://kondou.com/BS4/)