[utils] Correctly match class names in get_element[s]_by_class()

* reproduce CSS .classname behaviour ("bar" matches "bar", "foo bar baz", etc)
* add tests
This commit is contained in:
dirkf 2024-10-20 13:22:25 +01:00
parent 01b80a0802
commit 13b0e81f17
2 changed files with 9 additions and 3 deletions

View File

@ -1603,11 +1603,14 @@ Line 1
def test_get_element_by_class(self):
html = '''
<span class="foo bar">nice</span>
<span class="foo bar baz-bam">nice</span>
'''
self.assertEqual(get_element_by_class('foo', html), 'nice')
self.assertEqual(get_element_by_class('bar', html), 'nice')
self.assertEqual(get_element_by_class('no-such-class', html), None)
self.assertEqual(get_element_by_class('baz', html), None)
self.assertEqual(get_element_by_class('bam', html), None)
def test_get_element_by_attribute(self):
html = '''
@ -1626,10 +1629,13 @@ Line 1
def test_get_elements_by_class(self):
html = '''
<span class="foo bar">nice</span><span class="foo bar">also nice</span>
<span class="foo bar baz-bam">nice</span><span class="foo bar">also nice</span>
'''
self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
self.assertEqual(get_elements_by_class('bar', html), ['nice', 'also nice'])
self.assertEqual(get_elements_by_class('baz', html), [])
self.assertEqual(get_elements_by_class('bam', html), [])
self.assertEqual(get_elements_by_class('no-such-class', html), [])
def test_get_elements_by_attribute(self):

View File

@ -1960,7 +1960,7 @@ def get_element_by_attribute(attribute, value, html, escape_value=True):
def get_elements_by_class(class_name, html):
"""Return the content of all tags with the specified class in the passed HTML document as a list"""
return get_elements_by_attribute(
'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
'class', r'[^\'"]*(?<!-)\b%s\b(?!-)[^\'"]*' % re.escape(class_name),
html, escape_value=False)