inside a caption.
for tag in soup.find_all(attrs={'class': 'caption'}):
span = tag.find('span')
if span:
span.unwrap()
# Add a trailing period between a figure caption and its credit,
# where the caption doesn't already end in punctuation.
caption_classes = [
'body-elements__image-figcaption',
'header-teaser__image-details',
'caption',
'meta2',
]
for tag in soup.find_all(attrs={'class': caption_classes}):
if tag.string is None and tag.contents and tag.contents[0].string:
tag = tag.contents[0]
if tag.string:
text = str(tag.string).strip()
if text and text[-1] not in '.?!:':
tag.string.replace_with(text + '. ')
# Add a line break between an image and a following header-teaser.
for tag in soup.find_all(class_='header-teaser'):
tag.insert_before(soup.new_tag('br'))
# Wrap every image in its own , stripped of layout attributes.
for img_tag in soup.find_all('img'):
for attrib in ('height', 'width', 'border', 'align', 'style'):
if img_tag.has_attr(attrib):
del img_tag[attrib]
parent = img_tag.parent
index = parent.contents.index(img_tag)
img_tag.extract()
div_tag = soup.new_tag('div')
parent.insert(index, div_tag)
div_tag.append(img_tag)
return soup