Represents a found HTML tag with its attributes and contents.
| 504 | return "<!%s>" % NavigableString.__str__(self, encoding) |
| 505 | |
| 506 | class Tag(PageElement): |
| 507 | |
| 508 | """Represents a found HTML tag with its attributes and contents.""" |
| 509 | |
| 510 | def _convertEntities(self, match): |
| 511 | """Used in a call to re.sub to replace HTML, XML, and numeric |
| 512 | entities with the appropriate Unicode characters. If HTML |
| 513 | entities are being converted, any unrecognized entities are |
| 514 | escaped.""" |
| 515 | x = match.group(1) |
| 516 | if self.convertHTMLEntities and x in name2codepoint: |
| 517 | return unichr(name2codepoint[x]) |
| 518 | elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS: |
| 519 | if self.convertXMLEntities: |
| 520 | return self.XML_ENTITIES_TO_SPECIAL_CHARS[x] |
| 521 | else: |
| 522 | return u'&%s;' % x |
| 523 | elif len(x) > 0 and x[0] == '#': |
| 524 | # Handle numeric entities |
| 525 | if len(x) > 1 and x[1] == 'x': |
| 526 | return unichr(int(x[2:], 16)) |
| 527 | else: |
| 528 | return unichr(int(x[1:])) |
| 529 | |
| 530 | elif self.escapeUnrecognizedEntities: |
| 531 | return u'&%s;' % x |
| 532 | else: |
| 533 | return u'&%s;' % x |
| 534 | |
| 535 | def __init__(self, parser, name, attrs=None, parent=None, |
| 536 | previous=None): |
| 537 | "Basic constructor." |
| 538 | |
| 539 | # We don't actually store the parser object: that lets extracted |
| 540 | # chunks be garbage-collected |
| 541 | self.parserClass = parser.__class__ |
| 542 | self.isSelfClosing = parser.isSelfClosingTag(name) |
| 543 | self.name = name |
| 544 | if attrs is None: |
| 545 | attrs = [] |
| 546 | elif isinstance(attrs, dict): |
| 547 | attrs = attrs.items() |
| 548 | self.attrs = attrs |
| 549 | self.contents = [] |
| 550 | self.setup(parent, previous) |
| 551 | self.hidden = False |
| 552 | self.containsSubstitutions = False |
| 553 | self.convertHTMLEntities = parser.convertHTMLEntities |
| 554 | self.convertXMLEntities = parser.convertXMLEntities |
| 555 | self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities |
| 556 | |
| 557 | # Convert any HTML, XML, or numeric entities in the attribute values. |
| 558 | convert = lambda(k, val): (k, |
| 559 | re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);", |
| 560 | self._convertEntities, |
| 561 | val)) |
| 562 | self.attrs = map(convert, self.attrs) |
| 563 |
no outgoing calls