I am working on an HTML document to which I need to add certain classes to some elements. In the following code, I am adding class img-responsive
.
def add_img_class1(img_tag):
try:
img_tag['class'] = img_tag['class']+' img-responsive'
except KeyError:
img_tag['class'] = 'img-responsive'
return img_tag
def add_img_class2(img_tag):
if img_tag.has_attr('class'):
img_tag['class'] = img_tag['class']+' img-responsive'
else:
img_tag['class'] = 'img-responsive'
return img_tag
soup = BeautifulSoup(myhtml)
for img_tag in soup.find_all('img'):
img_tag = add_img_class1(img_tag) #or img_tag = add_img_class2(img_tag)
html = soup.prettify(soup.original_encoding)
with open("edited.html","wb") as file:
file.write(html)
- Both functions do same, however one uses exceptions and another has_attr from BS4. Which is better and why?
- Am I doing the right way of writing back to HTML? Or shall convert entire soup to UTF-8 (by
string.encode('UTF-8')
) and write it?