1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#定義一個MyParser繼承自HTMLParser
class
MyParser(HTMLParser):
re
=
[]
#放置結果
flg
=
0
#標誌,用以標記是否找到咱們須要的標籤
def
handle_starttag(
self
, tag, attrs):
if
tag
=
=
'h3'
:
#目標標籤
for
attr
in
attrs:
if
attr[
0
]
=
=
'class'
and
attr[
1
]
=
=
'tb-main-title'
:
#目標標籤具備的屬性
self
.flg
=
1
#符合條件則將標誌設置爲1
break
else
:
pass
def
handle_data(
self
, data):
if
self
.flg
=
=
1
:
self
.re.append(data.strip())
#若是標誌爲咱們須要的標誌,則將數據添加到列表中
self
.flg
=
0
#重置標誌,進行下次迭代
else
:
pass
my
=
MyParser()
my.feed(html)
|