[utils] Don't find classname as part of class="... x-classname ...", etc

Eg, in [1], the class with name 'plist-info' was found when searching for 'info'.

1. https://github.com/ytdl-org/youtube-dl/issues/30230
This commit is contained in:
df 2021-11-13 22:03:19 +00:00 committed by dirkf
parent a3fe1d1dc6
commit 58f15bb6c8
2 changed files with 12 additions and 5 deletions

View File

@ -1619,7 +1619,10 @@ 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="not-foo bar">nasty</span>
<span class="foo bar">nice</span>
<span class="bar foo">"also nice"</span>
<span class="bar foo-impostor">also nasty</span>
'''
self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])

View File

@ -1986,7 +1986,9 @@ 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 names can contain alphanumeric, -, _ and \ for escapes
# don't allow a word break at -
'class', r'(?:[\w\s\\-]*?[\w\s])?\b%s\b(?:[\w\s\\][\w\s\\-]*?)?' % re.escape(class_name),
html, escape_value=False)
@ -1997,11 +1999,13 @@ def get_elements_by_attribute(attribute, value, html, escape_value=True):
retlist = []
for m in re.finditer(r'''(?xs)
<([a-zA-Z0-9:._-]+)
<([a-zA-Z0-9:._-]+) # conservative pattern: HTML tags don't have :._-
# (?:\s[^>]+) # this seems to be simpler than the below and work the same?
(?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
\s+%s=['"]?%s['"]?
\s*\b%s\s*=\s*(?P<__q>'|"|\b)%s(?P=__q)
# (?:\s[^>]+)? # as above
(?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
\s*>
\s*>
(?P<content>.*?)
</\1>
''' % (re.escape(attribute), value), html):