Created
August 31, 2016 11:11
-
-
Save vasmedvedev/1dcb8a1211ee1e6b6b8fa144ad271ee5 to your computer and use it in GitHub Desktop.
Soup example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def insert_mid_related_articles(content, urls): | |
soup = bs4.BeautifulSoup(content, 'html.parser') | |
paragraphs = soup('p') | |
words_count = 0 | |
if len(paragraphs) > 1: | |
for p in paragraphs: | |
words = filter(bool, re.split('\W+', p.string)) | |
words_count += len(words) | |
if words_count > 300: | |
middle = len(paragraphs) / 2 | |
for n, p in enumerate(paragraphs, 1): | |
if n == middle: | |
ul = soup.new_tag('ul', **{'class': 'op-related-articles'}) | |
for url in urls: | |
li = soup.new_tag('li') | |
a = soup.new_tag('a', href=url) | |
li.append(a) | |
ul.append(li) | |
p.insert_after(ul) | |
return soup.decode(pretty_print=False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment