Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions pyquery/pyquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,15 @@ def remove_namespaces(self):
el.tag = el.tag.split('}', 1)[1]
return self

def _serialize_nodes(self, dumps, method):
# Text nodes from contents() cannot go through tostring.
has_text_nodes = any(isinstance(e, str) for e in self)
return ''.join(
e if isinstance(e, str) else dumps(
e, encoding=str, method=method, with_tail=not has_text_nodes)
for e in self
)

def __str__(self):
"""xml representation of current nodes::

Expand All @@ -353,12 +362,11 @@ def __str__(self):
<script>&lt;![[CDATA[ ]&gt;</script>

"""
return ''.join([etree.tostring(e, encoding=str) for e in self])
return self._serialize_nodes(etree.tostring, method='xml')

def __unicode__(self):
"""xml representation of current nodes"""
return u''.join([etree.tostring(e, encoding=str)
for e in self])
return self._serialize_nodes(etree.tostring, method='xml')

def __html__(self):
"""html representation of current nodes::
Expand All @@ -369,8 +377,7 @@ def __html__(self):
<script><![[CDATA[ ]></script>

"""
return u''.join([lxml.html.tostring(e, encoding=str)
for e in self])
return self._serialize_nodes(lxml.html.tostring, method='html')

def __repr__(self):
r = []
Expand Down
13 changes: 13 additions & 0 deletions tests/test_pyquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,19 @@ def test_comment(self):
self.assertEqual(doc.text(), 'bar')


class TestContentsStr(TestCase):

def test_str_contents_with_text_nodes(self):
doc = pq('hello <b>bold</b> world')
contents = doc.contents()
self.assertEqual(str(contents), 'hello <b>bold</b> world')
self.assertEqual(contents.__html__(), 'hello <b>bold</b> world')

def test_str_contents_text_only(self):
doc = pq('<div>only text</div>')
self.assertEqual(str(doc.contents()), 'only text')


class TestCallback(TestCase):
html = """
<ol>
Expand Down
Loading