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

回答編集履歴

3

a

2018/10/04 02:24

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ```python
4
4
  from bs4 import BeautifulSoup
5
+ from bs4.element import NavigableString
5
6
 
6
7
  html = '''
7
8
  <html>
@@ -22,8 +23,9 @@
22
23
 
23
24
  # br タグ直後の改行を削除
24
25
  for tag in soup.findAll('br'):
26
+ if isinstance(tag.next_sibling, NavigableString):
25
- text = tag.next_sibling.strip()
27
+ text = tag.next_sibling.strip()
26
- tag.next_sibling.replace_with(text)
28
+ tag.next_sibling.replace_with(text)
27
29
 
28
30
  # br タグを削除
29
31
  [tag.replaceWithChildren() for tag in soup.findAll('br')]

2

2018/10/04 02:24

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -7,8 +7,9 @@
7
7
  <html>
8
8
  <head></head>
9
9
  <body>
10
- <p>テスト<br>テスト<br></p>
11
- <p><strong>テスト</strong></p>
10
+ <td><strong>三菱<strong>UFJ<br/>
11
+ モルガン・<br/>
12
+ スタンレー証券</td>
12
13
  </body>
13
14
  <html>
14
15
  '''
@@ -16,13 +17,17 @@
16
17
  soup = BeautifulSoup(html, 'lxml')
17
18
  print('>>> before\n', soup)
18
19
 
20
+ # strong タグを削除
19
- ignore_tags = ['br', 'strong'] # 削除するタグ
21
+ [tag.replaceWithChildren() for tag in soup.findAll('strong')]
20
22
 
21
- # タグをコンテンツごと削除する場合
23
+ # br タグ直後の改行を削除
22
- #[tag.extract() for tag in soup.findAll(ignore_tags)]
24
+ for tag in soup.findAll('br'):
25
+ text = tag.next_sibling.strip()
26
+ tag.next_sibling.replace_with(text)
23
27
 
24
- # タグ削除するが、コンテンツは残す場合
28
+ # br タグ削除
25
- [tag.replaceWithChildren() for tag in soup.findAll(ignore_tags)]
29
+ [tag.replaceWithChildren() for tag in soup.findAll('br')]
30
+
26
31
  print('>>> after\n', soup)
27
32
  ```
28
33
 
@@ -31,8 +36,9 @@
31
36
  <html>
32
37
  <head></head>
33
38
  <body>
34
- <p>テスト<br/>テスト<br/></p>
39
+ <td><strong>三菱<strong>UFJ<br/>
40
+ モルガン・<br/>
35
- <p><strong>テスト</strong></p>
41
+ スタンレー証券</strong></strong></td>
36
42
  </body>
37
43
  </html>
38
44
 
@@ -40,8 +46,7 @@
40
46
  <html>
41
47
  <head></head>
42
48
  <body>
43
- <p>トテスト</p>
49
+ <td>三菱UFJモルガン・タンレー証券</td>
44
- <p>テスト</p>
45
50
  </body>
46
51
  </html>
47
52
  ```

1

2018/10/03 16:23

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -19,7 +19,7 @@
19
19
  ignore_tags = ['br', 'strong'] # 削除するタグ
20
20
 
21
21
  # タグをコンテンツごと削除する場合
22
- #[tag.replaceWithChildren() for tag in soup.findAll(ignore_tags)]
22
+ #[tag.extract() for tag in soup.findAll(ignore_tags)]
23
23
 
24
24
  # タグは削除するが、コンテンツは残す場合
25
25
  [tag.replaceWithChildren() for tag in soup.findAll(ignore_tags)]