find element in beautifulsoup by partial attribute value

Solutions on MaxInterview for find element in beautifulsoup by partial attribute value by the best coders in the world

showing results for - "find element in beautifulsoup by partial attribute value"
Natalia
15 Jan 2019
1# Use regex
2
3# suppose I have list of 'div' with 'class' as follows:
4# <div class='abcd bcde cdef efgh'>some content</div>
5# <div class='mnop bcde cdef efgh'>some content</div>
6# <div class='abcd pqrs cdef efgh'>some content</div>
7# <div class='hijk wxyz cdef efgh'>some content</div>
8
9# as observable the class value string of above div(s) ends with 'cdef efgh'
10# So to extract all these in a single list:
11
12from bs4 import BeautifulSoup
13import re # library for regex in python
14soup = BeautifulSoup(<your_html_response>, <parser_you_want_to_use>)
15elements = soup.find_all('div', {'class': re.compile(r'cdef efgh$')}) # $ means that 'cdef efgh' must is the ending of the string
16
17# Note: This was just one case. You can make almost any case with regex.
18# Learn more and experiment with regex at https://regex101.com/