Python HTMLParser的使用例子
2009-11-25 15:20
555 查看
#!/usr/bin/env python
import
sys
import
urllib
import
HTMLParser
class
CustomParser
(
HTMLParser
.
HTMLParser
)
:
selected
=
(
'
table
'
,
'
h1
'
,
'
font
'
,
'
ul
'
,
'
li
'
,
'
tr
'
,
'
td
'
,
'
a
'
)
def
reset
(
self
)
:
HTMLParser
.
HTMLParser
.
reset
(
self
)
self
.
_level_stack
=
[]
def
handle_starttag
(
self
,
tag
,
attrs
)
:
if
tag
in
CustomParser
.
selected
:
self
.
_level_stack
.
append
(
tag
)
def
handle_endtag
(
self
,
tag
)
:
if
self
.
_level_stack
/
and
tag
in
CustomParser
.
selected
/
and
tag
==
self
.
_level_stack
[
-
1
]
:
self
.
_level_stack
.
pop
()
def
handle_data
(
self
,
data
)
:
if
"
/
"
.
join
(
self
.
_level_stack
)
in
(
'
table/tr/td
'
,
'
table/tr/td/h1/font
'
,
'
table/tr/td/ul/li
'
)
:
print
self
.
_level_stack
,
data
if
len
(
sys
.
argv
)
>
1
:
params
=
urllib
.
urlencode
(
{
'
ip
'
:
sys
.
argv
[
1
]
,
'
action
'
:
2
}
)
else
:
params
=
None
content
=
unicode
(
urllib
.
urlopen
(
'
http://www.ip138.com/ips8.asp
'
,
params
)
.
read
()
,
'
GB2312
'
)
parser
=
CustomParser
()
parser
.
feed
(
content
)
parser
.
close
()
import
sys
import
urllib
import
HTMLParser
class
CustomParser
(
HTMLParser
.
HTMLParser
)
:
selected
=
(
'
table
'
,
'
h1
'
,
'
font
'
,
'
ul
'
,
'
li
'
,
'
tr
'
,
'
td
'
,
'
a
'
)
def
reset
(
self
)
:
HTMLParser
.
HTMLParser
.
reset
(
self
)
self
.
_level_stack
=
[]
def
handle_starttag
(
self
,
tag
,
attrs
)
:
if
tag
in
CustomParser
.
selected
:
self
.
_level_stack
.
append
(
tag
)
def
handle_endtag
(
self
,
tag
)
:
if
self
.
_level_stack
/
and
tag
in
CustomParser
.
selected
/
and
tag
==
self
.
_level_stack
[
-
1
]
:
self
.
_level_stack
.
pop
()
def
handle_data
(
self
,
data
)
:
if
"
/
"
.
join
(
self
.
_level_stack
)
in
(
'
table/tr/td
'
,
'
table/tr/td/h1/font
'
,
'
table/tr/td/ul/li
'
)
:
self
.
_level_stack
,
data
if
len
(
sys
.
argv
)
>
1
:
params
=
urllib
.
urlencode
(
{
'
ip
'
:
sys
.
argv
[
1
]
,
'
action
'
:
2
}
)
else
:
params
=
None
content
=
unicode
(
urllib
.
urlopen
(
'
http://www.ip138.com/ips8.asp
'
,
params
)
.
read
()
,
'
GB2312
'
)
parser
=
CustomParser
()
parser
.
feed
(
content
)
parser
.
close
()
相关文章推荐
- 一个Python HTMLParser的使用例子
- Python中的CURL PycURL使用例子
- 在python中实现生产者和消费者的例子(一):使用multiprocessing和pipe()
- [置顶] 使用Python3解压gz、tar、tgz、zip、rar五种格式的压缩文件例子
- python 中使用ftpmirror的例子
- python使用amqp的例子
- python使用正则表达式例子
- Python中使用scapy模拟数据包实现arp攻击、dns放大攻击例子
- python使用sqlite3的例子
- python进程与线程混合使用例子
- [Python]Python 使用 for 循环的小例子
- Python Pandas 库的使用例子
- #小练习 使用HTMLParser获取data时注意事项 分类: python 小练习 HTMLParser 2013-11-08 21:05 335人阅读 评论(0) 收藏
- Python中使用HTMLParser解析HTML文档
- Python random模块(获取随机数)常用方法和使用例子
- 使用python开发hadoop streaming程序及hadoop python网页抓取例子
- Python中使用glob和rmtree删除目录子目录及所有文件的例子
- 使用Python的HTMLParser解析HTML文本
- Python3 使用GUI统计代码量的例子
- java使用htmlparser提取网页纯文本例子