Python HTMLParser [英] Python HTMLParser

查看:79
本文介绍了Python HTMLParser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用HTMLParser解析一个html文档,我想在ap标签的开始和结束之间打印内容。

查看我的代码片段

  def handle_starttag(self,tag,attrs):
if tag =='p':
printTODO:打印内容

任何帮助都将不胜感激



Ruth

解决方案

我从 docs

  from HTMLParser import HTMLParser 

class MyHTMLParser(HTMLParser):

def handle_starttag(self,tag,attrs):
print遇到%s的开始标记%标记

def handle_endtag(self,tag):
print遇到%s标记的结尾%tag
$ b $ def handle_data(self,数据):
print遇到编辑数据%s%data

p = MyHTMLParser()
p.feed('< p> test< / p>')



-

 遇到ap tag 
遇到数据测试
遇到ap标签的结尾


I'm parsing a html document using HTMLParser and I want to print the contents between the start and end of a p tag

see my code snippet

    def handle_starttag(self, tag, attrs):
        if tag == 'p':
            print "TODO: print the contents"

Any help would be much appreciated

Ruth

解决方案

I extended the example from the docs:

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):

    def handle_starttag(self, tag, attrs):
        print "Encountered the beginning of a %s tag" % tag

    def handle_endtag(self, tag):
        print "Encountered the end of a %s tag" % tag

    def handle_data(self, data):
        print "Encountered data %s" % data

p = MyHTMLParser()
p.feed('<p>test</p>')

-

Encountered the beginning of a p tag
Encountered data test
Encountered the end of a p tag

这篇关于Python HTMLParser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆