回答編集履歴
1
isinstanceの方法も追加
answer
CHANGED
@@ -15,5 +15,30 @@
|
|
15
15
|
print("どちらでもないです")
|
16
16
|
```
|
17
17
|
|
18
|
+
追記(2017/03/27)
|
19
|
+
|
20
|
+
terapon さんからコメントでもらった内容も追記しておきます。 例えば、NavigableString の子クラスには `element.Comment` などが存在します。そういう親子関係にあるものも一緒にチェックしたいといった場合には、 isinstance を使う方がよりスマートにチェックできます。
|
21
|
+
|
22
|
+
```python
|
23
|
+
# -*- coding: utf-8 -*-
|
24
|
+
|
25
|
+
from bs4 import BeautifulSoup as soup
|
26
|
+
from bs4.element import NavigableString, Tag
|
27
|
+
|
28
|
+
# コメント(<!-- comment -->) が追加されている
|
29
|
+
html = '<span><!-- comment --><span class="a">1<span class="b"><span class="c">2</span></span></span></span>'
|
30
|
+
doc = soup(html, "lxml")
|
31
|
+
for item in doc.find_all("span"):
|
32
|
+
# element.Comment は NavigableString の子クラスなので、ここで一緒にチェックされる
|
33
|
+
# NavigableString の子クラス(孫クラス) は Comment以外にもいっぱいあるので、それらを全てここでチェックできる。
|
34
|
+
if isinstance(item.contents[0], NavigableString):
|
35
|
+
print("NavigableString(又はComment)です")
|
36
|
+
elif isinstance(item.contents[0], Tag):
|
37
|
+
print("Tagです")
|
38
|
+
else:
|
39
|
+
print("どちらでもないです")
|
40
|
+
```
|
41
|
+
|
18
42
|
参考
|
19
|
-
- [http://docs.python.jp/3.3/library/functions.html#type](http://docs.python.jp/3.3/library/functions.html#type)
|
43
|
+
- [http://docs.python.jp/3.3/library/functions.html#type](http://docs.python.jp/3.3/library/functions.html#type)
|
44
|
+
- [https://docs.python.jp/3/library/functions.html#isinstance](https://docs.python.jp/3/library/functions.html#isinstance)
|