- 浏览: 820990 次
- 性别:
- 来自: 北京、四川
文章分类
最新评论
-
sunbeamzheng:
总结的很好,好好看看。 拷贝问题确实很需要注意,特别是影不影响 ...
java深拷贝与浅拷贝 -
xmh8023:
...
获取POST数据的值 -
xmh8023:
我访问别的服务器怎么办?急求
获取POST数据的值 -
xmh8023:
String urlString="http://l ...
获取POST数据的值 -
lv12312:
Tomcat 7的老版本么?有bug的,https://iss ...
JMX问题
摘录了dive into python的例子
有两种方法,HTMLParser和SGMLParser
第一种:
第二种方式:
首先是一个基础类,和上面的方式一样
接着第二种方法具体的应用,解析的是新浪一个特定blog的文章的内容和标题代码如下:
有两种方法,HTMLParser和SGMLParser
第一种:
#-*-coding:utf-8-*- import HTMLParser #html解析,继承HTMLParser类 class MyHTMLParser(HTMLParser.HTMLParser): def _init(self): HTMLParser.HTMLParser.__init__(self); # 处理开始标签和结束标签 -- finish processing of start+end tag: <tag.../> def handle_startendtag(self, tag, attrs): self.handle_starttag(tag, attrs) self.handle_endtag(tag) #handle start tag #处理开始标签和结束标签 这里打印出a标签的href的属性值 def handle_starttag(self,tag, attrs): if tag=='a': for name,value in attrs: if name=='href': print value # 处理结束标签,比如</xx> -- handle end tag def handle_endtag(self,tag): pass; # 处理特殊字符串,就是以&#开头的,一般是内码表示的字符 -- handle character reference def handle_charref(self, name): pass # 处理一些特殊字符,以&开头的,比如 -- handle entity reference def handle_entityref(self, name): pass # 处理数据,就是<xx>data</xx>中间的那些数据 -- handle data def handle_data(self, data): pass # 处理注释 -- handle comment def handle_comment(self, data): pass # 处理<!开头的,比如<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" -- handle declaration def handle_decl(self, decl): pass # 处理形如<?instruction>的东西 -- handle processing instruction def handle_pi(self, data): pass a='<body><a href="www.163.com">test</a></body>' print a my=MyHTMLParser() my.feed(a) #结果为www.163.com
第二种方式:
首先是一个基础类,和上面的方式一样
#!/usr/bin/env python #-*-coding:utf-8-*- from sgmllib import SGMLParser import htmlentitydefs class BaseHTMLProcessor(SGMLParser): def reset(self): # extend (called by SGMLParser.__init__) self.pieces = [] SGMLParser.reset(self) #是一个开始一个块的 HTML 标记,象 <html>,<head>,<body> 或 <pre> 等,或是一个独一的标记, #象 <br> 或 <img> 等。当它找到一个开始标记 tagname,SGMLParser 将查找名为 start_tagname #或 do_tagname 的方法。例如,当它找到一个 <pre> 标记,它将查找一个 start_pre 或 do_pre 的方法。 #如果找到了,SGMLParser 会使用这个标记的属性列表来调用这个方法;否则,它用这个标记的名字和属性 #列表来调用 unknown_starttag 方法。 def unknown_starttag(self, tag, attrs): # called for each start tag # attrs is a list of (attr, value) tuples # e.g. for <pre class="screen">, tag="pre", attrs=[("class", "screen")] # Ideally we would like to reconstruct original tag and attributes, but # we may end up quoting attribute values that weren't quoted in the source # document, or we may change the type of quotes around the attribute value # (single to double quotes). # Note that improperly embedded non-HTML code (like client-side Javascript) # may be parsed incorrectly by the ancestor, causing runtime script errors. # All non-HTML code must be enclosed in HTML comment tags (<!-- code -->) # to ensure that it will pass through this parser unaltered (in handle_comment). strattrs = "".join([' %s="%s"' % (key, value) for key, value in attrs]) self.pieces.append("<%(tag)s%(strattrs)s>" % locals()) #是结束一个块的 HTML 标记,象 </html>,</head>,</body> 或 </pre> 等。 #当找到一个结束标记时,SGMLParser 将查找名为 end_tagname 的方法。如果找到, #SGMLParser 调用这个方法,否则它使用标记的名字来调用 unknown_endtag 。 def unknown_endtag(self, tag): # called for each end tag, e.g. for </pre>, tag will be "pre" # Reconstruct the original end tag. self.pieces.append("</%(tag)s>" % locals()) #用字符的十进制或等同的十六进制来表示的转义字符,象  。当 #找到,SGMLParser 使用十进制或等同的十六进制字符文本来调用 handle_charref 。 def handle_charref(self, ref): # called for each character reference, e.g. for " ", ref will be "160" # Reconstruct the original character reference. self.pieces.append("&#%(ref)s;" % locals()) #HTML 实体,象 ©。当找到,SGMLParser 使用 HTML 实体的名字来调用 handle_entityref 。 def handle_entityref(self, ref): # called for each entity reference, e.g. for "©", ref will be "copy" # Reconstruct the original entity reference. self.pieces.append("&%(ref)s" % locals()) # standard HTML entities are closed with a semicolon; other entities are not if htmlentitydefs.entitydefs.has_key(ref): self.pieces.append(";") #文本块。不满足其它 7 种类别的任何东西。当找到,SGMLParser 用文本来调用 handle_data。 def handle_data(self, text): # called for each block of plain text, i.e. outside of any tag and # not containing any character or entity references # Store the original text verbatim. #数据的处理 self.pieces.append(text) #HTML 注释, 包括在 <!-- ... -->之间。当找到,SGMLParser 用注释内容来调用 handle_comment def handle_comment(self, text): # called for each HTML comment, e.g. <!-- insert Javascript code here --> # Reconstruct the original comment. # It is especially important that the source document enclose client-side # code (like Javascript) within comments so it can pass through this # processor undisturbed; see comments in unknown_starttag for details. self.pieces.append("<!--%(text)s-->" % locals()) #HTML 处理指令,包括在 <? ... > 之间。当找到,SGMLParser 用处理指令内容来调用 handle_pi。 def handle_pi(self, text): # called for each processing instruction, e.g. <?instruction> # Reconstruct original processing instruction. self.pieces.append("<?%(text)s>" % locals()) #HTML 声明,如 DOCTYPE,包括在 <! ... >之间。当找到,SGMLParser 用声明内容来调用 handle_decl def handle_decl(self, text): # called for the DOCTYPE, if present, e.g. # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" # "http://www.w3.org/TR/html4/loose.dtd"> # Reconstruct original DOCTYPE self.pieces.append("<!%(text)s>" % locals()) def output(self): """Return processed HTML as a single string""" return "".join(self.pieces)
接着第二种方法具体的应用,解析的是新浪一个特定blog的文章的内容和标题代码如下:
#!/usr/bin/env python #coding:utf8 import re from BaseHTMLProcessor import BaseHTMLProcessor import urllib class Dialectizer(BaseHTMLProcessor): subs = () def reset(self): # extend (called from __init__ in ancestor) # Reset all data attributes self.verbatim = 0 BaseHTMLProcessor.reset(self) def unknown_starttag(self, tag, attrs): self.pieces.append("") def unknown_endtag(self, tag): self.pieces.append("") def start_title(self, attrs): self.pieces.append("title") def end_title(self): self.pieces.append("title") def start_p(self, attrs): self.pieces.append("\n") def end_p(self): self.pieces.append("") def start_div(self, attrs): strattrs = "".join([value for key, value in attrs]) self.pieces.append(strattrs) def end_div(self): self.pieces.append("div") def handle_data(self, text): self.pieces.append(self.verbatim and text or self.process(text)) def process(self, text): for fromPattern, toPattern in self.subs: text = re.sub(fromPattern, toPattern, text) return text def translate(url): import urllib sock = urllib.urlopen(url) htmlSource = sock.read() sock.close() parser = Dialectizer() #parser.subs=((r"本",r"aaa"),) parser.feed(htmlSource)#进行解析 parser.close() return parser.output() def test(url,filename): htmlSource=translate(url) #标题 title=htmlSource[re.search("title",htmlSource).end():] title=title[:re.search("title",title).end()-5] #内容 content=htmlSource[re.search("articleBody",htmlSource).end()+2:] content=content[:re.search("div",content).end()-3] content=re.sub(" ","",content) content=re.sub("nbsp;","",content) #文件名称 fileName=title; #输出的文件内容 fileContent=title+"\n\n\n"+content; fsock = open(filename, "wb") fsock.write(fileContent) fsock.close() if __name__ == "__main__": test("http://blog.sina.com.cn/s/blog_4bd7b9a20100cpgb.html",'test.txt')
- 代码.zip (3.9 KB)
- 下载次数: 32
发表评论
-
GAE发布
2010-04-24 10:42 2992很久没有写GAE的东西了,突然想写了点东西,很奇怪突然之间就传 ... -
django简单的入门例子
2009-04-30 10:40 15638django入门例子: 都是参考了网上的例子完成的~ 建立 ... -
摘自python cookbook2(文本文件)
2009-04-23 16:11 2548摘自python cookbook2(文本文件) url:ht ... -
摘自python cookbook1(字符串,字典)
2009-04-23 14:55 2558摘自python cookbook1(字符串,字典) url: ... -
flup安装问题
2009-03-23 19:02 9230在windows下flup一直安装不上,不知道为什么,在 ... -
xml的解析例子
2009-03-23 15:34 1443xml解析的一个例子,如下所示: #!/usr/bin/e ... -
python备份文件
2009-03-20 18:22 1462#-*-coding:utf-8-*- import o ... -
使用python下载日志
2009-03-17 18:48 2747第一步:主要是读取配置文件的内容,以及把各种数据存放到文件里 ... -
python控制流
2008-12-21 16:27 1253条件语句: if expression: sta ... -
python类型转换、数值操作
2008-12-21 16:20 53752python类型转换 函数 ... -
python学习之类型和对象
2008-12-21 16:14 8487序列是由非负整数索引 ... -
Django 的数据库查询
2008-12-14 14:21 49762class Blog(models.Model): ... -
摘自python的文档
2008-12-11 09:15 1242Boolean Operations — and, o ... -
python发送email
2008-11-11 15:46 8305第一种方法: # -*- coding: utf-8 -* ... -
python的简单文件操作
2008-10-28 09:15 1734#-*-coding:utf-8-*- import o ... -
python的数据库链接
2008-10-28 09:13 2088附件中是添加到mysql的windows下的库安装程序 ... -
用python实现的时间函数
2008-10-28 09:11 4203#-*-coding:utf-8-*- import d ...
相关推荐
只是解析url关键字测试代码用的一段url
其他说明: 这个工具是一个基本示例,使用了 Python 内置的 `urllib.parse` 模块来解析URL。你可以根据需要扩展工具的功能,例如支持更多URL部分、提供更详细的解析信息或自定义输出格式。用户需要输入要解析的URL,...
JSParser 使用Tornado和JSBeautifier的python 2.7脚本来解析JavaScript文件中的相对URL。 用于在执行安全研究或Bug赏金狩猎时轻松发现AJAX请求。
Python的urlparse有对url的解析,从而获得url中的参数列表 import urlparse urldata = "http://en.wikipedia.org/w/api.php?action=query&ctitle=FA" result = urlparse.urlparse(urldata) print result print ...
解析url用的类库: python2版本: from urlparse import urlparse import urllib python3版本: from urllib.parse import urlparse import urllib.request 研究了不同的url规则发现:只要在搜索关键字是用=嫁接的...
本文实例讲述了python对url格式解析的方法。分享给大家供大家参考。具体分析如下: python针对url格式的解析,可根据指定的完整URL解析出url地址的各个部分 from urlparse import urlparse url_str = ...
adblockparser, 用于Adblock加滤波器的python 解析器 adblockparser adblockparser 是一个用于处理 Adblock加过滤规则的软件包。 它可以解析Adblock加过滤器和 MATCH url 。安装pip install adblock
批量将域名转成ip,为了避免误差,该工具同时使用dig工具和python自带的gethostbyname_ex工具解析域名,并且最大化的收集所有ip。 如果使用windows需要安装dig工具(mac或者linux忽略)。 安装教程:...
yarl 这个模块提供了用于url解析和更改的便捷的URL类
主要讲述python 中如何解析一个url的信息.
由于页面给的数据的以json格式的,所以如何解析页面上的数据,从而获得我们想要的字段是我们首先考虑的问题。一般来说,当我们从一个网页上拿下来数据,就是一个字符串,比如:复制代码 代码如下:url_data = urllib2...
Python 爬虫之超链接 url中含有中文出错及解决办法 python3.5 爬虫错误: UnicodeEncodeError: 'ascii' codec can't encode characters 这个错误是由于超链接中含有中文引起的,超链接默认是用ascii编码的,所以不...
本文实例讲述了Python Django框架url反向解析实现动态生成对应的url链接。分享给大家供大家参考,具体如下: url反向解析:根据url路由规则,动态生成对应的url链接 (防止硬编码)。 url反向解析应用在两个地方:...
python学习(解析nginx埋点日志,解析json数据格式,url爬虫,redis集群删key)
主要介绍了Python HTMLParser模块解析html获取url实例,HTMLParser是python用来解析html的模块,HTMLParser采用的是一种事件驱动的模式,需要的朋友可以参考下
使用Python解析来自Github的信息 链接到 动机 这是我第一次解析网页。 我有从GitHub获取统计信息的想法,但是做另一个机器人很无聊。 因此,我决定直接使用我的个人资料页面。 :smiling_face_with_smiling_eyes: ...
在Python中可以使用urllib对网页进行爬取,然后利用Beautiful Soup对爬取的页面进行解析,提取出所有的URL。 什么是Beautiful Soup? Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树...