Skip to content

Commit

Permalink
Escape angle brackets in textareas
Browse files Browse the repository at this point in the history
  • Loading branch information
jcushman committed Aug 2, 2021
1 parent d69b4ac commit 1bcf107
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
6 changes: 3 additions & 3 deletions pyquery/pyquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from urllib.parse import urlencode
from urllib.parse import urljoin
from .openers import url_opener
from .text import extract_text
from .text import extract_text, escape_brackets
from copy import deepcopy
from html import escape
from lxml import etree
Expand Down Expand Up @@ -993,7 +993,7 @@ def val(self, value=no_default):
def _get_value(tag):
# <textarea>
if tag.tag == 'textarea':
return self._copy(tag).html()
return escape_brackets(self._copy(tag).html())
# <select>
elif tag.tag == 'select':
if 'multiple' in tag.attrib:
Expand Down Expand Up @@ -1177,7 +1177,7 @@ def text(self, value=no_default, **kwargs):
if not self:
return ''
return ' '.join(
self._copy(tag).html() if tag.tag == 'textarea' else
escape_brackets(self._copy(tag).html()) if tag.tag == 'textarea' else
extract_text(tag, **kwargs) for tag in self
)

Expand Down
5 changes: 5 additions & 0 deletions pyquery/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,8 @@ def extract_text(dom, block_symbol='\n', sep_symbol='\n', squash_space=True):
if squash_space:
result = result.strip()
return result


def escape_brackets(text):
# escape just angle brackets, for use in textarea contents
return text.replace('<', '&lt;').replace('>', '&gt;')
9 changes: 6 additions & 3 deletions tests/test_pyquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,13 +530,16 @@ def test_val_for_textarea(self):
# Note: jQuery still returns 'Spam' here.
self.assertEqual(d('#textarea-single').text(), '42')

multi_expected = '''Spam\n<b>Eggs</b>\nBacon'''
# as in jquery, .val() and .text() come back with angle brackets escaped
# for html tags within <textarea>
multi_expected = '''Spam\n&lt;b&gt;Eggs&lt;/b&gt;\nBacon'''
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

0 comments on commit 1bcf107

Please sign in to comment.