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&quot;'&amp;&lt;&gt;z'

html.unescape(s)

对转义的结果进行还原

Convert all named and numeric character references (e.g. &gt;, >, &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&quot;'&amp;&lt;&gt;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. &gt;), 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 &gt; 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 : h1

The 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 : script

Parsing 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('&gt;>>')
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 : span

Parsing 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解析模块的更多相关文章

  1. 浩哥解析MyBatis源码(十一)——Parsing解析模块之通用标记解析器(GenericTokenParser)与标记处理器(TokenHandler)

    原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/6724223.html 1.回顾 上面的几篇解析了类型模块,在MyBatis中类型模块包含的 ...

  2. python命令行参数解析模块argparse和docopt

    http://blog.csdn.net/pipisorry/article/details/53046471 还有其他两个模块实现这一功能,getopt(等同于C语言中的getopt())和弃用的o ...

  3. MyBatis源码解析(十一)——Parsing解析模块之通用标记解析器(GenericTokenParser)与标记处理器(TokenHandler)

    原创作品,可以转载,但是请标注出处地址:http://www.cnblogs.com/V1haoge/p/6724223.html 1.回顾 上面的几篇解析了类型模块,在MyBatis中类型模块包含的 ...

  4. python命令行解析模块--argparse

    python命令行解析模块--argparse 目录 简介 详解ArgumentParser方法 详解add_argument方法 参考文档: https://www.jianshu.com/p/aa ...

  5. $命令行参数解析模块argparse的用法

    argparse是python内置的命令行参数解析模块,可以用来为程序配置功能丰富的命令行参数,方便使用,本文总结一下其基本用法. 测试脚本 把以下脚本存在argtest.py文件中: # codin ...

  6. 细谈HTML解析模块

     细谈HTML解析模块 Html在网页中所占的位置,用一个简单直观的图给展示一下:    

  7. DRF框架(二)——解析模块(parsers)、异常模块(exception_handler)、响应模块(Response)、三大序列化组件介绍、Serializer组件(序列化与反序列化使用)

    解析模块 为什么要配置解析模块 1)drf给我们提供了多种解析数据包方式的解析类 form-data/urlencoded/json 2)我们可以通过配置来控制前台提交的哪些格式的数据后台在解析,哪些 ...

  8. drf框架 - 解析模块 | 异常模块 | 响应模块

    解析模块 为什么要配置解析模块 1)drf给我们提供了多种解析数据包方式的解析类 2)我们可以通过配置,来控制前台提交的哪些格式的数据后台在解析,哪些数据不解析 3)全局配置就是针对每一个视图类,局部 ...

  9. Python命令行参数解析模块getopt使用实例

    Python命令行参数解析模块getopt使用实例 这篇文章主要介绍了Python命令行参数解析模块getopt使用实例,本文讲解了使用语法格式.短选项参数实例.长选项参数实例等内容,需要的朋友可以参 ...

  10. 第二章、drf框架 - 请求模块 | 渲染模块 解析模块 | 异常模块 | 响应模块 (详细版)

    目录 drf框架 - 请求模块 | 渲染模块 解析模块 | 异常模块 | 响应模块 Postman接口工具 drf框架 注册rest_framework drf框架风格 drf请求生命周期 请求模块 ...

随机推荐

  1. python学习笔记5.1-核心类型-集合set类型[转]

    转自:http://blog.csdn.net/business122/article/details/7541486 python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系 ...

  2. 华为S5300系列升级固件S5300SI-V100R005C00SPC100.cc

    这个固件附带了web,注意,这个插件是升级V200的必经固件,所以必须升级为此固件之后才能往下升级. 升级小插曲: 1.升级的使用使用Windows,不要用Mac或者Linux,因为从Mac/Linu ...

  3. hdu 2112 HDU Today (floyd算法)

    这道题貌似在原来学长给我们的搞的小比赛中出过! 这次又让我遇到,果断拿下! 不过方法很蠢,跑了1000多ms,虽然要求5000ms以内! 题目就是给你一些位置之间的距离,然后再让你求特定的两点之间的距 ...

  4. 运用Android ROM Manager应用安装ClockworkMod Recovery的详细教程

    在安装ClockworkMod Recovery恢复模式之前,建议先认识下Google Android平台的ClockworkMod Recovery恢复模式 对于Android ROM Manage ...

  5. XBee Level Shifting

    http://www.faludi.com/bwsn/xbee-level-shifting/ The XBee communication (RX/TX) pins definitely opera ...

  6. C 常量的类型

    http://bbs.csdn.net/topics/380028485 整型常量的类型是下列相应表中第一个能表示其值的类型: int --> long int --> long long ...

  7. maven 之dependencyManagement 和 pluginManagement

    一个大中型Java项目中,一般由若干个module组成,各个module各司其职,担任整个工程中不同角色.大多数情况下,大多数module都会用到相同的jar包,或者插件.如果每个module中都引入 ...

  8. mybatis如何根据mapper接口生成其实现类

    SpringBoot集成mybatis mybatis的statement的解析与加载 mybatis如何根据mapper接口生成其实现类 mybatis的mapper返回map结果集 mybatis ...

  9. JAVA自定义注解SpringAOP

    原文:https://my.oschina.net/wangnian/blog/801348 前言:Annotation(注解)是JDK5.0及以后版本引入的,它的作用就是负责注解其他注解.现在开发过 ...

  10. 【微信小程序】在微信开发工具上七牛云的图片可以看到,但是在真机上看不到的原因解决

    在开发微信小程序过程中,在微信开发者工具上,七牛云的图片都可以展示出来,但是在真机上,七牛云的图片却展示不出来,也没有报404找不到或者不能加载图片的问题, 必须保证: 1.图片是用image加载的: ...