Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape entities in html() output #221

Merged
merged 2 commits into from
Aug 6, 2021
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
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

- Add nextUntil method

- Fix escaping of top-level element text in ``.html()`` output


1.4.3 (2020-11-21)
------------------
Expand Down
5 changes: 3 additions & 2 deletions pyquery/pyquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from .openers import url_opener
from .text import extract_text
from copy import deepcopy
from html import escape
from lxml import etree
import lxml.html
import inspect
Expand Down Expand Up @@ -1085,9 +1086,9 @@ def html(self, value=no_default, **kwargs):
return None
tag = self[0]
children = tag.getchildren()
html = escape(tag.text or '', quote=False)
if not children:
return tag.text or ''
html = tag.text or ''
return html
if 'encoding' not in kwargs:
kwargs['encoding'] = str
html += u''.join([etree.tostring(e, **kwargs)
Expand Down
12 changes: 10 additions & 2 deletions tests/test_pyquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,9 +534,10 @@ def test_val_for_textarea(self):
self.assertEqual(d('#textarea-multi').val(), multi_expected)
self.assertEqual(d('#textarea-multi').text(), multi_expected)
multi_new = '''Bacon\n<b>Eggs</b>\nSpam'''
multi_new_expected = '''Bacon\n&lt;b&gt;Eggs&lt;/b&gt;\nSpam'''
d('#textarea-multi').val(multi_new)
self.assertEqual(d('#textarea-multi').val(), multi_new)
self.assertEqual(d('#textarea-multi').text(), multi_new)
self.assertEqual(d('#textarea-multi').val(), multi_new_expected)
self.assertEqual(d('#textarea-multi').text(), multi_new_expected)

def test_val_for_select(self):
d = pq(self.html4)
Expand Down Expand Up @@ -622,6 +623,13 @@ def test_html_replacement(self):
self.assertEqual(new_html, expected)
self.assertIn(replacement, new_html)

def test_html_escape(self):
inner_html = 'encoded &lt;script&gt; tag with "quotes".' \
'<span>nested &lt;tag&gt;</span>'
html = '<div>' + inner_html + '</div>'
d = pq(html)
self.assertEqual(d.html(), inner_html)


class TestAjax(TestCase):

Expand Down