Get or set the html representation of sub nodes. Get the text value:: >>> d = PyQuery(' toto ') >>> print(d.html()) toto Extra args are passed to ``lxml.etree.tostring``:: >>> d = PyQuery(' <sp
(self, value=no_default, **kwargs)
| 1069 | return self |
| 1070 | |
| 1071 | def html(self, value=no_default, **kwargs): |
| 1072 | """Get or set the html representation of sub nodes. |
| 1073 | |
| 1074 | Get the text value:: |
| 1075 | |
| 1076 | >>> d = PyQuery('<div><span>toto</span></div>') |
| 1077 | >>> print(d.html()) |
| 1078 | <span>toto</span> |
| 1079 | |
| 1080 | Extra args are passed to ``lxml.etree.tostring``:: |
| 1081 | |
| 1082 | >>> d = PyQuery('<div><span></span></div>') |
| 1083 | >>> print(d.html()) |
| 1084 | <span/> |
| 1085 | >>> print(d.html(method='html')) |
| 1086 | <span></span> |
| 1087 | |
| 1088 | Set the text value:: |
| 1089 | |
| 1090 | >>> d.html('<span>Youhou !</span>') |
| 1091 | [<div>] |
| 1092 | >>> print(d) |
| 1093 | <div><span>Youhou !</span></div> |
| 1094 | """ |
| 1095 | if value is no_default: |
| 1096 | if not self: |
| 1097 | return None |
| 1098 | tag = self[0] |
| 1099 | children = tag.getchildren() |
| 1100 | html = escape(tag.text or '', quote=False) |
| 1101 | if not children: |
| 1102 | return html |
| 1103 | if 'encoding' not in kwargs: |
| 1104 | kwargs['encoding'] = str |
| 1105 | html += u''.join([etree.tostring(e, **kwargs) |
| 1106 | for e in children]) |
| 1107 | return html |
| 1108 | else: |
| 1109 | if isinstance(value, self.__class__): |
| 1110 | new_html = str(value) |
| 1111 | elif isinstance(value, basestring): |
| 1112 | new_html = value |
| 1113 | elif not value: |
| 1114 | new_html = '' |
| 1115 | else: |
| 1116 | raise ValueError(type(value)) |
| 1117 | |
| 1118 | for tag in self: |
| 1119 | for child in tag.getchildren(): |
| 1120 | tag.remove(child) |
| 1121 | root = fromstring( |
| 1122 | u'<root>' + new_html + u'</root>', |
| 1123 | self.parser)[0] |
| 1124 | children = root.getchildren() |
| 1125 | if children: |
| 1126 | tag.extend(children) |
| 1127 | tag.text = root.text |
| 1128 | return self |