回答編集履歴

1

isinstanceの方法も追加

2017/03/26 03:05

投稿

tell_k
tell_k

スコア2120

test CHANGED
@@ -32,6 +32,56 @@
32
32
 
33
33
 
34
34
 
35
+ 追記(2017/03/27)  
36
+
37
+
38
+
39
+ terapon さんからコメントでもらった内容も追記しておきます。 例えば、NavigableString の子クラスには `element.Comment` などが存在します。そういう親子関係にあるものも一緒にチェックしたいといった場合には、 isinstance を使う方がよりスマートにチェックできます。
40
+
41
+
42
+
43
+ ```python
44
+
45
+ # -*- coding: utf-8 -*-
46
+
47
+
48
+
49
+ from bs4 import BeautifulSoup as soup
50
+
51
+ from bs4.element import NavigableString, Tag
52
+
53
+
54
+
55
+ # コメント(<!-- comment -->) が追加されている
56
+
57
+ html = '<span><!-- comment --><span class="a">1<span class="b"><span class="c">2</span></span></span></span>'
58
+
59
+ doc = soup(html, "lxml")
60
+
61
+ for item in doc.find_all("span"):
62
+
63
+ # element.Comment は NavigableString の子クラスなので、ここで一緒にチェックされる
64
+
65
+ # NavigableString の子クラス(孫クラス) は Comment以外にもいっぱいあるので、それらを全てここでチェックできる。
66
+
67
+ if isinstance(item.contents[0], NavigableString):
68
+
69
+ print("NavigableString(又はComment)です")
70
+
71
+ elif isinstance(item.contents[0], Tag):
72
+
73
+ print("Tagです")
74
+
75
+ else:
76
+
77
+ print("どちらでもないです")
78
+
79
+ ```
80
+
81
+
82
+
35
83
  参考
36
84
 
37
85
  - [http://docs.python.jp/3.3/library/functions.html#type](http://docs.python.jp/3.3/library/functions.html#type)
86
+
87
+ - [https://docs.python.jp/3/library/functions.html#isinstance](https://docs.python.jp/3/library/functions.html#isinstance)