无聊之人--除了技术,还是技术,你懂得
分类: Python/Ruby
2011-08-29 18:40:21
8.7. Quoting attribute values
A common question on is “I have a bunch of HTML documents with unquoted attribute values, and I want to properly quote them all. How can I do this?”[4] (This is generally precipitated by a project manager who has found the HTML-is-a-standard religion joining a large project and proclaiming that all pages must validate against an HTML validator. Unquoted attribute values are a common violation of the HTML standard.) Whatever the reason, unquoted attribute values are easy to fix by feeding HTML through BaseHTMLProcessor.
在com.lang.python上面一个非常普遍的问题就;我有一大堆html文件,它们包含了未引用的(属性值(未曾使用单引号,或是双引号),我想对它们进行适当的引用。我该怎那么办呢?(这个问题曾被一个项目经理提前预见过,它发现html是一个标准的信仰,它对项目进行整合,同时该标准还宣称所有的网页都必须满足html合法性。未曾引用的属性就是一个很常见的对html标准的违背)不论出于什么原因,未曾引用的属性值通过使用 BaseHTMLProcessor还是很容易修补的。
BaseHTMLProcessor consumes HTML (since it's descended from SGMLParser) and produces equivalent HTML, but the HTML output is not identical to the input. Tags and attribute names will end up in lowercase, even if they started in uppercase or mixed case, and attribute values will be enclosed in double quotes, even if they started in single quotes or with no quotes at all. It is this last side effect that you can take advantage of.
BaseHTMLProcessor以html为输入(因为它是从SGMLParser继承的),然后产生等价的html,但是输入的html同输入的html并不完全相同。标签和属性名都是以小写形式结束,即使它们以大写形式或是大小写混合的形式开始,而且所有的属性值都必须包括双引号内,即使它们刚开始的使用的是单引号,或者根本没有使用引号。这是你可以充分利用的最后的副作用了。
Example 8.16. Quoting attribute values
例8.16 引用的属性值
Note that the attribute values of the href attributes in the tags are not properly quoted. (Also note that you're using triple quotes for something other than a doc string. And directly in the IDE, no less. They're very useful.) 注意: 中href属性的属性值并没有被恰当的引用。(同样值得注意的是:对于某些标签你在使用的是三元组引号而不是一个doc string.如果直接在IDE中,引号不会少的。IDE非常有用) |
|
Feed the parser. 给parser传递输入 |
|
Using the output function defined in BaseHTMLProcessor, you get the output as a single string, complete with quoted attribute values. While this may seem anti-climactic, think about how much has actually happened here: SGMLParser parsed the entire HTML document, breaking it down into tags, refs, data, and so forth; BaseHTMLProcessor used those elements to reconstruct pieces of HTML (which are still stored in parser.pieces, if you want to see them); finally, you called parser.output, which joined all the pieces of HTML into one string. 使用定义在BaseHTMLProcessor中的函数输出,你得到的输出是字符串形式的,属性值完全包含在引号内。尽管这看起来有点虎头蛇尾,想想这里到底发生了多少事情:SGMLParser解析了整个html文档,分解成标签,引用,数据,等等。BaseHTMLProcessor使用这些元素来重建html的片段(仍然存储在parser.pieces,如果你打算看他们的话);最后你调用了parser.output,它将所有的html片段连接成了一个字符串。 anti-climactic虎头蛇尾的 |