HTML解析模块
import html
html.escape(s, quote=True)
对特殊字符进行转义
Convert the characters &, < and > in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. If the optional flag quote is true, the characters (") and (') are also translated; this helps for inclusion in an HTML attribute value delimited by quotes, as in <a href="...">.
->html.escape('''a"'&<>z''')
->'a"'&<>z'
html.unescape(s)
对转义的结果进行还原
Convert all named and numeric character references (e.g. >, >, &x3e;) in the string s to the corresponding unicode characters. This function uses the rules defined by the HTML 5 standard for both valid and invalid character references, and the list of HTML 5 named character references.
->html.unescape('a"'&<>z')
->'a"\'&<>z'
import html.entities
This module defines four dictionaries, html5, name2codepoint, codepoint2name, and entitydefs.
- html.entities.html5
-
A dictionary that maps HTML5 named character references [1] to the equivalent Unicode character(s), e.g. html5['gt;'] == '>'. Note that the trailing semicolon is included in the name (e.g. 'gt;'), however some of the names are accepted by the standard even without the semicolon: in this case the name is present with and without the ';'. See also html.unescape().
- html.entities.entitydefs
-
A dictionary mapping XHTML 1.0 entity definitions to their replacement text in ISO Latin-1.
- html.entities.name2codepoint
-
A dictionary that maps HTML entity names to the Unicode codepoints.
- html.entities.codepoint2name
-
A dictionary that maps Unicode codepoints to HTML entity names.
import html.parser
This module defines a class HTMLParser which serves as the basis for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
class html.parser.HTMLParser(strict=False, *, convert_charrefs=False)
Create a parser instance.
If convert_charrefs is True (default: False), all character references (except the ones in script/style elements) are automatically converted to the corresponding Unicode characters. The use of convert_charrefs=True is encouraged and will become the default in Python 3.5.
An HTMLParser instance is fed HTML data and calls handler methods when start tags, end tags, text, comments, and other markup elements are encountered. The user should subclass HTMLParser and override its methods to implement the desired behavior.
This parser does not check that end tags match start tags or call the end-tag handler for elements which are closed implicitly by closing an outer element.
Example HTML Parser Application
As a basic example, below is a simple HTML parser that uses the HTMLParser class to print out start tags, end tags, and data as they are encountered:
from html.parser import HTMLParser class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Encountered a start tag:", tag)
def handle_endtag(self, tag):
print("Encountered an end tag :", tag)
def handle_data(self, data):
print("Encountered some data :", data) parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
'<body><h1>Parse me!</h1></body></html>')The output will then be:
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h1
Encountered some data : Parse me!
Encountered an end tag : h1
Encountered an end tag : body
Encountered an end tag : html
HTMLParser Methods
HTMLParser instances have the following methods:
- HTMLParser.feed(data)
-
Feed some text to the parser. It is processed insofar as it consists of complete elements; incomplete data is buffered until more data is fed or close() is called. data must be str.
- HTMLParser.close()
-
Force processing of all buffered data as if it were followed by an end-of-file mark. This method may be redefined by a derived class to define additional processing at the end of the input, but the redefined version should always call the HTMLParser base class method close().
- HTMLParser.reset()
-
Reset the instance. Loses all unprocessed data. This is called implicitly at instantiation time.
- HTMLParser.getpos()
-
Return current line number and offset.
- HTMLParser.get_starttag_text()
-
Return the text of the most recently opened start tag. This should not normally be needed for structured processing, but may be useful in dealing with HTML “as deployed” or for re-generating input with minimal changes (whitespace between attributes can be preserved, etc.).
The following methods are called when data or markup elements are encountered and they are meant to be overridden in a subclass. The base class implementations do nothing (except for handle_startendtag()):
- HTMLParser.handle_starttag(tag, attrs)
-
This method is called to handle the start of a tag (e.g. <div id="main">).
The tag argument is the name of the tag converted to lower case. The attrs argument is a list of (name, value) pairs containing the attributes found inside the tag’s <> brackets. The name will be translated to lower case, and quotes in the value have been removed, and character and entity references have been replaced.
For instance, for the tag <A HREF="http://www.cwi.nl/">, this method would be called as handle_starttag('a', [('href', 'http://www.cwi.nl/')]).
All entity references from html.entities are replaced in the attribute values.
- HTMLParser.handle_endtag(tag)
-
This method is called to handle the end tag of an element (e.g. </div>).
The tag argument is the name of the tag converted to lower case.
- HTMLParser.handle_startendtag(tag, attrs)
-
Similar to handle_starttag(), but called when the parser encounters an XHTML-style empty tag (<img ... />). This method may be overridden by subclasses which require this particular lexical information; the default implementation simply calls handle_starttag() and handle_endtag().
- HTMLParser.handle_data(data)
-
This method is called to process arbitrary data (e.g. text nodes and the content of <script>...</script> and <style>...</style>).
- HTMLParser.handle_entityref(name)
-
This method is called to process a named character reference of the form &name; (e.g. >), where name is a general entity reference (e.g. 'gt'). This method is never called if convert_charrefs is True.
- HTMLParser.handle_charref(name)
-
This method is called to process decimal and hexadecimal numeric character references of the form &#NNN; and &#xNNN;. For example, the decimal equivalent for > is >, whereas the hexadecimal is >; in this case the method will receive '62' or 'x3E'. This method is never called if convert_charrefs is True.
- HTMLParser.handle_comment(data)
-
This method is called when a comment is encountered (e.g. <!--comment-->).
For example, the comment <!-- comment --> will cause this method to be called with the argument ' comment '.
The content of Internet Explorer conditional comments (condcoms) will also be sent to this method, so, for <!--[if IE 9]>IE9-specific content<![endif]-->, this method will receive '[if IE 9]>IE-specific content<![endif]'.
- HTMLParser.handle_decl(decl)
-
This method is called to handle an HTML doctype declaration (e.g. <!DOCTYPE html>).
The decl parameter will be the entire contents of the declaration inside the <!...> markup (e.g. 'DOCTYPE html').
- HTMLParser.handle_pi(data)
-
Method called when a processing instruction is encountered. The data parameter will contain the entire processing instruction. For example, for the processing instruction <?proc color='red'>, this method would be called as handle_pi("proc color='red'"). It is intended to be overridden by a derived class; the base class implementation does nothing.
Note
The HTMLParser class uses the SGML syntactic rules for processing instructions. An XHTML processing instruction using the trailing '?' will cause the '?' to be included in data.
- HTMLParser.unknown_decl(data)
-
This method is called when an unrecognized declaration is read by the parser.
The data parameter will be the entire contents of the declaration inside the <![...]> markup. It is sometimes useful to be overridden by a derived class. The base class implementation raises an HTMLParseError when strict is True.
Examples
The following class implements a parser that will be used to illustrate more examples:
from html.parser import HTMLParser
from html.entities import name2codepoint class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Start tag:", tag)
for attr in attrs:
print(" attr:", attr)
def handle_endtag(self, tag):
print("End tag :", tag)
def handle_data(self, data):
print("Data :", data)
def handle_comment(self, data):
print("Comment :", data)
def handle_entityref(self, name):
c = chr(name2codepoint[name])
print("Named ent:", c)
def handle_charref(self, name):
if name.startswith('x'):
c = chr(int(name[1:], 16))
else:
c = chr(int(name))
print("Num ent :", c)
def handle_decl(self, data):
print("Decl :", data) parser = MyHTMLParser()Parsing a doctype:
>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
... '"http://www.w3.org/TR/html4/strict.dtd">')
Decl : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"Parsing an element with a few attributes and a title:
>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
attr: ('src', 'python-logo.png')
attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h1>Python</h1>')
Start tag: h1
Data : Python
End tag : h1The content of script and style elements is returned as is, without further parsing:
>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
attr: ('type', 'text/css')
Data : #python { color: green }
End tag : style
>>>
>>> parser.feed('<script type="text/javascript">'
... 'alert("<strong>hello!</strong>");</script>')
Start tag: script
attr: ('type', 'text/javascript')
Data : alert("<strong>hello!</strong>");
End tag : scriptParsing comments:
>>> parser.feed('<!-- a comment -->'
... '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment : a comment
Comment : [if IE 9]>IE-specific content<![endif]Parsing named and numeric character references and converting them to the correct char (note: these 3 references are all equivalent to '>'):
>>> parser.feed('>>>')
Named ent: >
Num ent : >
Num ent : >Feeding incomplete chunks to feed() works, but handle_data() might be called more than once (unless convert_charrefs is set to True):
>>> for chunk in ['<sp', 'an>buff', 'ered ', 'text</s', 'pan>']:
... parser.feed(chunk)
...
Start tag: span
Data : buff
Data : ered
Data : text
End tag : spanParsing invalid HTML (e.g. unquoted attributes) also works:
>>> parser.feed('<p><a class="link" href=#main>tag soup</p ></a>')
Start tag: p
Start tag: a
attr: ('class', 'link')
attr: ('href', '#main')
Data : tag soup
End tag : p
End tag : a
HTML解析模块的更多相关文章
- 浩哥解析MyBatis源码(十一)——Parsing解析模块之通用标记解析器(GenericTokenParser)与标记处理器(TokenHandler)
原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/6724223.html 1.回顾 上面的几篇解析了类型模块,在MyBatis中类型模块包含的 ...
- python命令行参数解析模块argparse和docopt
http://blog.csdn.net/pipisorry/article/details/53046471 还有其他两个模块实现这一功能,getopt(等同于C语言中的getopt())和弃用的o ...
- MyBatis源码解析(十一)——Parsing解析模块之通用标记解析器(GenericTokenParser)与标记处理器(TokenHandler)
原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/6724223.html 1.回顾 上面的几篇解析了类型模块,在MyBatis中类型模块包含的 ...
- python命令行解析模块--argparse
python命令行解析模块--argparse 目录 简介 详解ArgumentParser方法 详解add_argument方法 参考文档: https://www.jianshu.com/p/aa ...
- $命令行参数解析模块argparse的用法
argparse是python内置的命令行参数解析模块,可以用来为程序配置功能丰富的命令行参数,方便使用,本文总结一下其基本用法. 测试脚本 把以下脚本存在argtest.py文件中: # codin ...
- 细谈HTML解析模块
细谈HTML解析模块 Html在网页中所占的位置,用一个简单直观的图给展示一下:
- DRF框架(二)——解析模块(parsers)、异常模块(exception_handler)、响应模块(Response)、三大序列化组件介绍、Serializer组件(序列化与反序列化使用)
解析模块 为什么要配置解析模块 1)drf给我们提供了多种解析数据包方式的解析类 form-data/urlencoded/json 2)我们可以通过配置来控制前台提交的哪些格式的数据后台在解析,哪些 ...
- drf框架 - 解析模块 | 异常模块 | 响应模块
解析模块 为什么要配置解析模块 1)drf给我们提供了多种解析数据包方式的解析类 2)我们可以通过配置,来控制前台提交的哪些格式的数据后台在解析,哪些数据不解析 3)全局配置就是针对每一个视图类,局部 ...
- Python命令行参数解析模块getopt使用实例
Python命令行参数解析模块getopt使用实例 这篇文章主要介绍了Python命令行参数解析模块getopt使用实例,本文讲解了使用语法格式.短选项参数实例.长选项参数实例等内容,需要的朋友可以参 ...
- 第二章、drf框架 - 请求模块 | 渲染模块 解析模块 | 异常模块 | 响应模块 (详细版)
目录 drf框架 - 请求模块 | 渲染模块 解析模块 | 异常模块 | 响应模块 Postman接口工具 drf框架 注册rest_framework drf框架风格 drf请求生命周期 请求模块 ...
随机推荐
- Git_忽略特殊文件
有些时候,你必须把某些文件放到Git工作目录中,但又不能提交它们,比如保存了数据库密码的配置文件啦,等等,每次git status都会显示“Untracked files ...”,有强迫症的童鞋心里 ...
- Android音效SoundPool问题:soundpool 1 not retry
Android音效SoundPool问题:soundpool 1 not retry 今天开发中要用到SoundPool,遇到soundpool 1 not retry无法播放声音,MediaPlay ...
- 使用Bootstrap 3开发响应式网站实践07,页脚
页脚部分比较简单,把一个12列的Grid切分. <footer> <div class="container"> <div class="r ...
- java内存模型知识点汇总
1.像windows/linux这种操作系统中,自带jvm么?以方便java程序的运行? 答:是的,一般操作系统都自带jvm的.但不带jdk,也就是说java的运行环境有,但编译环境没有. 1.jav ...
- Python 必备神器
1. pip 用来包管理 文档:https://pip.pypa.io/en/latest/installing.html # 安装,可指定版本号(sudo) pip install Django== ...
- 如何开启解决android studio的模拟器的问题
来自:http://jingyan.baidu.com/article/03b2f78c0a19e75ea237ae24.html 有的时候因为电脑系统或者是安装的一些问题我们可能需要对症下药的解决模 ...
- iOS Sprite Kit最新特性Physics Field虚拟物理场Swift測试
在WWDC2014上,Sprite Kit又有了非常多新的提升! 当中一个非常有意思的东西就是Physics Field!也就是物理场! 这意味着我们在Sprite kit上编写虚拟物理场的游戏将变得 ...
- 《Head First 设计模式》学习笔记——策略模型
我们全都使用别人设计好的库与框架.我们讨论库与框架.利用他们的API编译成我们的程序.享受运用别人的代码所带来的长处.看看java api它所带来的功能:网络.GUI.IO等.库与框架长久以来,一直扮 ...
- [翻译] 用 ObjectiveSugar 扩展NSArray NSDictionary NSSet NSNumber
source - https://github.com/supermarin/ObjectiveSugar Look like a girl, act like a lady, think like ...
- Android之应用内部实现国际化
这篇文章也提供了应用内部转换语言的方法: http://blog.csdn.net/sodino/article/details/6596709 .1和2的方法是一样的,然而还是会调整了手机的语言设置 ...