I'm new to both Python and BeautifulSoup. I'm trying to figure out how to match only the tags that are <div> elements that contain a certain matched pattern of text belonging to an attribute. For example, all cases where the 'id' : 'testid', or everywhere the 'class' : 'title'.
This is what I have so far:
def cleanup(filename):
fh = open(filename, "r")
soup = BeautifulSoup(fh, 'html.parser')
for div_tag in soup.find('div', {'class':'title'}):
h2_tag = soup.h2_tag("h2")
div_tag.div.replace_with(h2_tag)
del div_tag['class']
f = open("/tmp/filename.modified", "w")
f.write(soup.prettify(formatter="html5"))
f.close()
Once I can match all those particular elements, at that point I can figure out how to manipulate the attributes (delete the class, rename the tag itself from <div> to <h1>, etc). So I'm aware that actual part of the cleanup probably doesn't work with how it is currently.