Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Read by thought-leaders and decision-makers around the world. Phone Number: +1-650-246-9381 Email: pub@towardsai.net
228 Park Avenue South New York, NY 10003 United States
Website: Publisher: https://towardsai.net/#publisher Diversity Policy: https://towardsai.net/about Ethics Policy: https://towardsai.net/about Masthead: https://towardsai.net/about
Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Founders: Roberto Iriondo, , Job Title: Co-founder and Advisor Works for: Towards AI, Inc. Follow Roberto: X, LinkedIn, GitHub, Google Scholar, Towards AI Profile, Medium, ML@CMU, FreeCodeCamp, Crunchbase, Bloomberg, Roberto Iriondo, Generative AI Lab, Generative AI Lab Denis Piffaretti, Job Title: Co-founder Works for: Towards AI, Inc. Louie Peters, Job Title: Co-founder Works for: Towards AI, Inc. Louis-François Bouchard, Job Title: Co-founder Works for: Towards AI, Inc. Cover:
Towards AI Cover
Logo:
Towards AI Logo
Areas Served: Worldwide Alternate Name: Towards AI, Inc. Alternate Name: Towards AI Co. Alternate Name: towards ai Alternate Name: towardsai Alternate Name: towards.ai Alternate Name: tai Alternate Name: toward ai Alternate Name: toward.ai Alternate Name: Towards AI, Inc. Alternate Name: towardsai.net Alternate Name: pub.towardsai.net
5 stars – based on 497 reviews

Frequently Used, Contextual References

TODO: Remember to copy unique IDs whenever it needs used. i.e., URL: 304b2e42315e

Resources

Take our 85+ lesson From Beginner to Advanced LLM Developer Certification: From choosing a project to deploying a working product this is the most comprehensive and practical LLM course out there!

Publication

Scraping Your Medium Stories
Latest   Machine Learning

Scraping Your Medium Stories

Last Updated on July 24, 2023 by Editorial Team

Author(s): Joaquin de Castro

Originally published on Towards AI.

Data Mining, Programming

While learning about and exploring the power of web scraping

In the “good old days” Medium allowed us to have custom websites for our publications. Unfortunately, this functionality has been recently deprecated.

Nonetheless, as developers, we are resourceful and not so easily discouraged.

We can use web scraping to get details on each of our Medium stories (title, description, link, feature image, and even tags!) and display them on a separate website.

This process will be divided into two articles. The first part will focus solely on scraping the articles, where we can discover the power of web scraping. In the second article, we will use our scraped data to add and update entries to a database and automate and even schedule the scraping process.

Web Scraping

Web scraping is the process of extracting data from a website. We can use it to ‘scrape’ social media posts, news articles, and in our case, Medium stories. To help us out, we can use a couple of libraries, including BeautifulSoup and requests. With these, it really only takes three to four lines to scrape almost anything:

url='https://medium.com'
response = requests.get(url)
content = BeautifulSoup(response.content, 'html.parser')
some_tag = content.find_all('tag')

The first line just defines the URL which we will be getting data from. The second line actually accesses the URL, the same way a human would paste a URL in a search engine. The third line parses the Response Object returned from the second line and gives us HTML content we can actually read. And finally, the fourth line searches the content for a specific HTML tag.

Of course, a web scraper is rarely ever just four lines. We could want to search for different tags scattered throughout the web page, and format them so that they are human-readable. But the entire process remains the same.

Getting our hands dirty with code

So without any more delay, let’s get into the actual code. Again, our goal is to scrape an author’s Medium stories and provide the relevant information on each.

The URL

As we saw above, we need to have an actual web page where we can get all that juicy data. We could try our Medium profile page (like https://medium.com/@joaquindecastro), but the information there is buried in messy source code, which can be a nuisance to parse. Instead, we can use the RSS feed provided by Medium for each author (like https://medium.com/feed/@joaquindecastro).

When we open this page, we can see that the information is already laid out in XML tags. Not only is this much easier to scrape, but we can avoid inspecting any source code entirely!

url='https://medium.com/feed/@joaquindecastro'

Parsing With Requests and BeautifulSoup

Next, we can simply follow the process outlined above to get the content of the URL:

response = requests.get(url)
content = BeautifulSoup(response.content, 'html.parser')

Now, before we get into retrieving information, notice some texts are nested in XML character data blocks (<![CDATA[]]>). Let’s remove this since we will be parsing the feed as HTML.

content = str(content).replace('<![CDATA[','').replace(']]>','')
content = BeautifulSoup(content, 'html.parser')

U+1F4A1 Remember to convert the content variable to a string first and back to a BeautifulSoup object, without doing so we will run into attribute and type errors

Get A List of Recent Articles

Looking at the RSS feed, we see that information on each article is found in an <item> tag.

A snippet of my RSS feed<item>
<title>
<![CDATA[ The Powers of Two: Why Is 1 + 2 + 4 + 8 + … = -1 ]]>
</title>
<description>
<![CDATA[ <div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/cantors-paradise/the-powers-of-two-why-is-1-2-4-8-1-19d8f00be228?source=rss-46b79b6c143b------2"><img src="https://cdn-images-1.medium.com/max/2048/1*geeybYiAeCd1vFkKuO75lA@2x.jpeg" width="2048"></a></p><p class="medium-feed-snippet">On calculating infinite divergent series sums</p><p class="medium-feed-link"><a href="https://medium.com/cantors-paradise/the-powers-of-two-why-is-1-2-4-8-1-19d8f00be228?source=rss-46b79b6c143b------2">Continue reading on Cantor’s Paradise »</a></p></div> ]]>
</description>
<link>https://medium.com/cantors-paradise/the-powers-of-two-why-is-1-2-4-8-1-19d8f00be228?source=rss-46b79b6c143b------2</link>
<guid isPermaLink="false">https://medium.com/p/19d8f00be228</guid>
<category>
<![CDATA[ science ]]>
</category>
<category>
<![CDATA[ infinity ]]>
</category>
<category>
<![CDATA[ math ]]>
</category>
<category>
<![CDATA[ education ]]>
</category>
<category>
<![CDATA[ numbers ]]>
</category>
<dc:creator>
<![CDATA[ Joaquin de Castro ]]>
</dc:creator>
<pubDate>Wed, 01 Jul 2020 08:36:11 GMT</pubDate>
<atom:updated>2020-07-01T10:45:28.172Z</atom:updated>
</item>

Since we want to get information for each article, we should iterate over all these item tags.

To get an ‘iterable’ object, we can use BeautifulSoup’s find_all attribute like so:

articles = content.find_all('item')

Then, we can loop over this:

for a in articles:
# GET TITLE
# GET SUBTITLE
# GET DATA
...

Title

Firstly, it would make sense to get the title of each article. Scanning the XML document, we can observe that all titles are found in a <title> tag

<item>
<title><![CDATA[ The Powers of Two: Why Is 1 + 2 + 4 + 8 + … = -1 ]]></title>
...

To retrieve this, all we have to do is use BeautifulSoup’s ‘find’ attribute (there’s only one title per article, so no need to use find_all)

title = a.find('title').text

U+1F4A1 The .text just removes the tags, in this case <title> and </title>, leaving us only with the text that we need

Subtitle

<item>
...
<description>
<![CDATA[ <div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/cantors-paradise/the-powers-of-two-why-is-1-2-4-8-1-19d8f00be228?source=rss-46b79b6c143b------2"><img src="https://cdn-images-1.medium.com/max/2048/1*geeybYiAeCd1vFkKuO75lA@2x.jpeg" width="2048"></a></p><p class="medium-feed-snippet">On calculating infinite divergent series sums</p><p class="medium-feed-link"><a href="https://medium.com/cantors-paradise/the-powers-of-two-why-is-1-2-4-8-1-19d8f00be228?source=rss-46b79b6c143b------2">Continue reading on Cantor’s Paradise »</a></p></div> ]]>
</description>
...

It’s good practice to put a subheading on our Medium articles, so readers know what to expect from an article. Looking back at our RSS feed, we can find our subtitle in a paragraph tag. But there are multiple paragraph tags in the page, so we need a way to distinguish it from the others. This can be accomplished with the unique class=“medium-feed-snippet” – which we can see is assigned only to the subtitle – and the attrs parameter.

for subtitle in a.find_all('p', attrs={'class':'medium-feed-snippet'}):
subtitle = subtitle.text

We used find_all here because using find leads to an attribute error:

subtitle = a.find('subtitle').text
AttributeError: 'NoneType' object has no attribute 'text'

Feature Image

<item>
...
<description>
...
<img src="https://cdn-images-1.medium.com/max/2048/1*geeybYiAeCd1vFkKuO75lA@2x.jpeg" width="2048">
...

The feed also provides us with the image source. We can just apply what we’ve done so far, except we use a [‘src’] key to get only the link to the image:

for img in a.find_all('img', src=True):
img = img['src']

Link To The Actual Medium Article

<item>
...
<link>https://medium.com/cantors-paradise/the-powers-of-two-why-is-1-2-4-8-1-19d8f00be228?source=rss-46b79b6c143b------2</link>
...

To keep things short, we won’t be scraping the entire article content, but we can get the link to the medium article. This is helpful later on when we list these articles on a separate website (say, a blog or portfolio), where we can redirect viewers to the full article. Again, it’s almost the exact same thing as with the feature image, except we use [‘href’] key instead.

for link in a.find_all('a', href=True):
link = link['href']

Publisher

Finding the publication where the story was published can be a bit more tricky. The publication name is not directly specified. But with a bit of ingenuity, we can see that the publication can be found through the article link. Hence, given the publications, a user submits to, and the respective publication slug (the ‘towards-artificial-intelligence’ part in medium.com/towards-artificial-intelligence), we can run through the possible publications as follows:

if 'towards-artificial-intelligence' in link:
publisher = "Towards AI"
elif 'cantors-paradise' in link:
publisher = "Cantor's Paradise"
elif 'mindreform' in link:
publisher = 'MindReform'

Tags

<category>
<![CDATA[ science ]]>
</category>
<category>
<![CDATA[ infinity ]]>
</category>
<category>
<![CDATA[ math ]]>
</category>
<category>
<![CDATA[ education ]]>
</category>
<category>
<![CDATA[ numbers ]]>
</category>

Scraping the Medium tags can help is incorporate a search function in our website later on. Upon scanning the document, we see that the tags for an article are each nested in a <category> tag. Since an article can have multiple tags, we’ll use find_all and append each tag to a list like so

tags = []
for tag in a.find_all('category'):
tag = tag.text
tags.append(tag)

Date

<item>
...
<pubDate>Wed, 01 Jul 2020 08:36:11 GMT</pubDate>
...

And last but not the least, the date. We have to be careful when parsing the date. Not only should we take note of the date format in the document, but also the format we want to convert it to (especially when dealing with databases). We will use the datatime module to do this.

import datetime # DON'T FORGET!date = a.find('pubdate').text
date = str(date).replace(' GMT','') # REMOVE GMT STRING
date = datetime.strptime(date, '%a, %d %b %Y %H:%M:%S') # CONVERT date TO DATETIME OBJECT
date = date.strftime('%Y-%m-%d') # CONVERT TO DJANGO DateField FORMAT

As we can see from within the <pubdate> tag, the date is in the format “weekday, day month year hours:minutes:seconds GMT”. GMT can be disregarded, so we’ll remove that entirely. With this, let’s convert the remaining data into code strptime() can understand (check this link for full date format code).

'%a, %d %b %Y %H:%M:%S'

U+1F4A1 Note that decimal numbers in the RSS feed are zero-padded (e.g. 01 instead of just 1)

Finally, let’s convert it into our desired format, I simply followed Django’s default DateField format, which is “year-month-day” or

'%Y-%m-%d'

Organizing Data

That’s all!

Now we have scrumptious data on each of our Medium articles. Unfortunately, the feed does not give all our articles, but this shouldn’t be a problem in the future since we will be scraping this regularly.

To keep our output clean, let’s pass all of this data into a dictionary for each article, and in turn, pass that into a list:

 ... # EVERYTHING WE DID UP THERE
# PUT ALL INFO IN A DICTIONARY
article_info = {
'title':title,
'img':img,
'date':date,
'subtitle':subtitle,
'publisher':publisher,
'link':link,
'tags':tags
}
# PUT article_info IN article_all
articles_all.append(article_info)
print(articles_all)

The Final Code

Here’s all our code put together. The final result is a list of all our articles — each represented by a dictionary containing the title, subtitle, image, link, date, publisher, and tags.

import requests
from bs4 import BeautifulSoup
import pandas
from datetime import datetime
# GET ACTUAL CONTENT
url='https://medium.com/feed/@joaquindecastro'
response = requests.get(url)
content = BeautifulSoup(response.content, 'html.parser')
# REMOVE UNNECESSARY STRINGS
content = str(content).replace('<![CDATA[','').replace(']]>','')
content = BeautifulSoup(content, 'html.parser')
# GET LIST OF ALL ARTICLES
# FOUND IN <item> TAG
articles = content.find_all('item')
# CREATE ARRAY FOR ALL article_info
articles_all = []
# GET ARTICLE INFO PER ARTICLE
for a in articles:
# GET TITLE
title = str(a.find('title').text)
# GET SUBTITLE
for subtitle in a.find_all('p', attrs={'class':'medium-feed-snippet'}):
subtitle = subtitle.text
# GET IMG SOURCE
for img in a.find_all('img', src=True):
img = img['src']
# GET DATE
date = a.find('pubdate').text
date = str(date).replace(' GMT','') # REMOVE GMT STRING
date = datetime.strptime(date, '%a, %d %b %Y %H:%M:%S') # CONVERT date TO DATETIME OBJECT
date = date.strftime('%Y-%m-%d') # CONVERT TO DJANGO DateField FORMAT
# GET LINK TO MEDIUM ARTICLE
for href in a.find_all('a', href=True):
link = href['href']
# GET PUBLISHER BASED ON LINK (eg medium.com/my-publication/article-slug)
if 'towards-artificial-intelligence' in link:
publisher = "Towards AI"
elif 'cantors-paradise' in link:
publisher = "Cantor's Paradise"
elif 'mindreform' in link:
publisher = 'MindReform'
# GET LIST OF TAGS
tags = []
for tag in a.find_all('category'):
tag = tag.text
tags.append(tag)
# PUT ALL INFO IN A DICTIONARY
article_info = {
'title':title,
'img':img,
'date':date,
'subtitle':subtitle,
'publisher':publisher,
'link':link,
'tags':tags
}
# PUT article_info IN article_all
articles_all.append(article_info)
print(articles_all)

Here’s the Github repository: https://github.com/JoaquindeCastro/medium_scraper

Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.

Published via Towards AI

Feedback ↓

Sign Up for the Course
`; } else { console.error('Element with id="subscribe" not found within the page with class "home".'); } } }); // Remove duplicate text from articles /* Backup: 09/11/24 function removeDuplicateText() { const elements = document.querySelectorAll('h1, h2, h3, h4, h5, strong'); // Select the desired elements const seenTexts = new Set(); // A set to keep track of seen texts const tagCounters = {}; // Object to track instances of each tag elements.forEach(el => { const tagName = el.tagName.toLowerCase(); // Get the tag name (e.g., 'h1', 'h2', etc.) // Initialize a counter for each tag if not already done if (!tagCounters[tagName]) { tagCounters[tagName] = 0; } // Only process the first 10 elements of each tag type if (tagCounters[tagName] >= 2) { return; // Skip if the number of elements exceeds 10 } const text = el.textContent.trim(); // Get the text content const words = text.split(/\s+/); // Split the text into words if (words.length >= 4) { // Ensure at least 4 words const significantPart = words.slice(0, 5).join(' '); // Get first 5 words for matching // Check if the text (not the tag) has been seen before if (seenTexts.has(significantPart)) { // console.log('Duplicate found, removing:', el); // Log duplicate el.remove(); // Remove duplicate element } else { seenTexts.add(significantPart); // Add the text to the set } } tagCounters[tagName]++; // Increment the counter for this tag }); } removeDuplicateText(); */ // Remove duplicate text from articles function removeDuplicateText() { const elements = document.querySelectorAll('h1, h2, h3, h4, h5, strong'); // Select the desired elements const seenTexts = new Set(); // A set to keep track of seen texts const tagCounters = {}; // Object to track instances of each tag // List of classes to be excluded const excludedClasses = ['medium-author', 'post-widget-title']; elements.forEach(el => { // Skip elements with any of the excluded classes if (excludedClasses.some(cls => el.classList.contains(cls))) { return; // Skip this element if it has any of the excluded classes } const tagName = el.tagName.toLowerCase(); // Get the tag name (e.g., 'h1', 'h2', etc.) // Initialize a counter for each tag if not already done if (!tagCounters[tagName]) { tagCounters[tagName] = 0; } // Only process the first 10 elements of each tag type if (tagCounters[tagName] >= 10) { return; // Skip if the number of elements exceeds 10 } const text = el.textContent.trim(); // Get the text content const words = text.split(/\s+/); // Split the text into words if (words.length >= 4) { // Ensure at least 4 words const significantPart = words.slice(0, 5).join(' '); // Get first 5 words for matching // Check if the text (not the tag) has been seen before if (seenTexts.has(significantPart)) { // console.log('Duplicate found, removing:', el); // Log duplicate el.remove(); // Remove duplicate element } else { seenTexts.add(significantPart); // Add the text to the set } } tagCounters[tagName]++; // Increment the counter for this tag }); } removeDuplicateText(); //Remove unnecessary text in blog excerpts document.querySelectorAll('.blog p').forEach(function(paragraph) { // Replace the unwanted text pattern for each paragraph paragraph.innerHTML = paragraph.innerHTML .replace(/Author\(s\): [\w\s]+ Originally published on Towards AI\.?/g, '') // Removes 'Author(s): XYZ Originally published on Towards AI' .replace(/This member-only story is on us\. Upgrade to access all of Medium\./g, ''); // Removes 'This member-only story...' }); //Load ionic icons and cache them if ('localStorage' in window && window['localStorage'] !== null) { const cssLink = 'https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css'; const storedCss = localStorage.getItem('ionicons'); if (storedCss) { loadCSS(storedCss); } else { fetch(cssLink).then(response => response.text()).then(css => { localStorage.setItem('ionicons', css); loadCSS(css); }); } } function loadCSS(css) { const style = document.createElement('style'); style.innerHTML = css; document.head.appendChild(style); } //Remove elements from imported content automatically function removeStrongFromHeadings() { const elements = document.querySelectorAll('h1, h2, h3, h4, h5, h6, span'); elements.forEach(el => { const strongTags = el.querySelectorAll('strong'); strongTags.forEach(strongTag => { while (strongTag.firstChild) { strongTag.parentNode.insertBefore(strongTag.firstChild, strongTag); } strongTag.remove(); }); }); } removeStrongFromHeadings(); "use strict"; window.onload = () => { /* //This is an object for each category of subjects and in that there are kewords and link to the keywods let keywordsAndLinks = { //you can add more categories and define their keywords and add a link ds: { keywords: [ //you can add more keywords here they are detected and replaced with achor tag automatically 'data science', 'Data science', 'Data Science', 'data Science', 'DATA SCIENCE', ], //we will replace the linktext with the keyword later on in the code //you can easily change links for each category here //(include class="ml-link" and linktext) link: 'linktext', }, ml: { keywords: [ //Add more keywords 'machine learning', 'Machine learning', 'Machine Learning', 'machine Learning', 'MACHINE LEARNING', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, ai: { keywords: [ 'artificial intelligence', 'Artificial intelligence', 'Artificial Intelligence', 'artificial Intelligence', 'ARTIFICIAL INTELLIGENCE', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, nl: { keywords: [ 'NLP', 'nlp', 'natural language processing', 'Natural Language Processing', 'NATURAL LANGUAGE PROCESSING', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, des: { keywords: [ 'data engineering services', 'Data Engineering Services', 'DATA ENGINEERING SERVICES', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, td: { keywords: [ 'training data', 'Training Data', 'training Data', 'TRAINING DATA', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, ias: { keywords: [ 'image annotation services', 'Image annotation services', 'image Annotation services', 'image annotation Services', 'Image Annotation Services', 'IMAGE ANNOTATION SERVICES', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, l: { keywords: [ 'labeling', 'labelling', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, pbp: { keywords: [ 'previous blog posts', 'previous blog post', 'latest', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, mlc: { keywords: [ 'machine learning course', 'machine learning class', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, }; //Articles to skip let articleIdsToSkip = ['post-2651', 'post-3414', 'post-3540']; //keyword with its related achortag is recieved here along with article id function searchAndReplace(keyword, anchorTag, articleId) { //selects the h3 h4 and p tags that are inside of the article let content = document.querySelector(`#${articleId} .entry-content`); //replaces the "linktext" in achor tag with the keyword that will be searched and replaced let newLink = anchorTag.replace('linktext', keyword); //regular expression to search keyword var re = new RegExp('(' + keyword + ')', 'g'); //this replaces the keywords in h3 h4 and p tags content with achor tag content.innerHTML = content.innerHTML.replace(re, newLink); } function articleFilter(keyword, anchorTag) { //gets all the articles var articles = document.querySelectorAll('article'); //if its zero or less then there are no articles if (articles.length > 0) { for (let x = 0; x < articles.length; x++) { //articles to skip is an array in which there are ids of articles which should not get effected //if the current article's id is also in that array then do not call search and replace with its data if (!articleIdsToSkip.includes(articles[x].id)) { //search and replace is called on articles which should get effected searchAndReplace(keyword, anchorTag, articles[x].id, key); } else { console.log( `Cannot replace the keywords in article with id ${articles[x].id}` ); } } } else { console.log('No articles found.'); } } let key; //not part of script, added for (key in keywordsAndLinks) { //key is the object in keywords and links object i.e ds, ml, ai for (let i = 0; i < keywordsAndLinks[key].keywords.length; i++) { //keywordsAndLinks[key].keywords is the array of keywords for key (ds, ml, ai) //keywordsAndLinks[key].keywords[i] is the keyword and keywordsAndLinks[key].link is the link //keyword and link is sent to searchreplace where it is then replaced using regular expression and replace function articleFilter( keywordsAndLinks[key].keywords[i], keywordsAndLinks[key].link ); } } function cleanLinks() { // (making smal functions is for DRY) this function gets the links and only keeps the first 2 and from the rest removes the anchor tag and replaces it with its text function removeLinks(links) { if (links.length > 1) { for (let i = 2; i < links.length; i++) { links[i].outerHTML = links[i].textContent; } } } //arrays which will contain all the achor tags found with the class (ds-link, ml-link, ailink) in each article inserted using search and replace let dslinks; let mllinks; let ailinks; let nllinks; let deslinks; let tdlinks; let iaslinks; let llinks; let pbplinks; let mlclinks; const content = document.querySelectorAll('article'); //all articles content.forEach((c) => { //to skip the articles with specific ids if (!articleIdsToSkip.includes(c.id)) { //getting all the anchor tags in each article one by one dslinks = document.querySelectorAll(`#${c.id} .entry-content a.ds-link`); mllinks = document.querySelectorAll(`#${c.id} .entry-content a.ml-link`); ailinks = document.querySelectorAll(`#${c.id} .entry-content a.ai-link`); nllinks = document.querySelectorAll(`#${c.id} .entry-content a.ntrl-link`); deslinks = document.querySelectorAll(`#${c.id} .entry-content a.des-link`); tdlinks = document.querySelectorAll(`#${c.id} .entry-content a.td-link`); iaslinks = document.querySelectorAll(`#${c.id} .entry-content a.ias-link`); mlclinks = document.querySelectorAll(`#${c.id} .entry-content a.mlc-link`); llinks = document.querySelectorAll(`#${c.id} .entry-content a.l-link`); pbplinks = document.querySelectorAll(`#${c.id} .entry-content a.pbp-link`); //sending the anchor tags list of each article one by one to remove extra anchor tags removeLinks(dslinks); removeLinks(mllinks); removeLinks(ailinks); removeLinks(nllinks); removeLinks(deslinks); removeLinks(tdlinks); removeLinks(iaslinks); removeLinks(mlclinks); removeLinks(llinks); removeLinks(pbplinks); } }); } //To remove extra achor tags of each category (ds, ml, ai) and only have 2 of each category per article cleanLinks(); */ //Recommended Articles var ctaLinks = [ /* ' ' + '

Subscribe to our AI newsletter!

' + */ '

Take our 85+ lesson From Beginner to Advanced LLM Developer Certification: From choosing a project to deploying a working product this is the most comprehensive and practical LLM course out there!

'+ '

Towards AI has published Building LLMs for Production—our 470+ page guide to mastering LLMs with practical projects and expert insights!

' + '
' + '' + '' + '

Note: Content contains the views of the contributing authors and not Towards AI.
Disclosure: This website may contain sponsored content and affiliate links.

' + 'Discover Your Dream AI Career at Towards AI Jobs' + '

Towards AI has built a jobs board tailored specifically to Machine Learning and Data Science Jobs and Skills. Our software searches for live AI jobs each hour, labels and categorises them and makes them easily searchable. Explore over 10,000 live jobs today with Towards AI Jobs!

' + '
' + '

🔥 Recommended Articles 🔥

' + 'Why Become an LLM Developer? Launching Towards AI’s New One-Stop Conversion Course'+ 'Testing Launchpad.sh: A Container-based GPU Cloud for Inference and Fine-tuning'+ 'The Top 13 AI-Powered CRM Platforms
' + 'Top 11 AI Call Center Software for 2024
' + 'Learn Prompting 101—Prompt Engineering Course
' + 'Explore Leading Cloud Providers for GPU-Powered LLM Training
' + 'Best AI Communities for Artificial Intelligence Enthusiasts
' + 'Best Workstations for Deep Learning
' + 'Best Laptops for Deep Learning
' + 'Best Machine Learning Books
' + 'Machine Learning Algorithms
' + 'Neural Networks Tutorial
' + 'Best Public Datasets for Machine Learning
' + 'Neural Network Types
' + 'NLP Tutorial
' + 'Best Data Science Books
' + 'Monte Carlo Simulation Tutorial
' + 'Recommender System Tutorial
' + 'Linear Algebra for Deep Learning Tutorial
' + 'Google Colab Introduction
' + 'Decision Trees in Machine Learning
' + 'Principal Component Analysis (PCA) Tutorial
' + 'Linear Regression from Zero to Hero
'+ '

', /* + '

Join thousands of data leaders on the AI newsletter. It’s free, we don’t spam, and we never share your email address. Keep up to date with the latest work in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.

',*/ ]; var replaceText = { '': '', '': '', '
': '
' + ctaLinks + '
', }; Object.keys(replaceText).forEach((txtorig) => { //txtorig is the key in replacetext object const txtnew = replaceText[txtorig]; //txtnew is the value of the key in replacetext object let entryFooter = document.querySelector('article .entry-footer'); if (document.querySelectorAll('.single-post').length > 0) { //console.log('Article found.'); const text = entryFooter.innerHTML; entryFooter.innerHTML = text.replace(txtorig, txtnew); } else { // console.log('Article not found.'); //removing comment 09/04/24 } }); var css = document.createElement('style'); css.type = 'text/css'; css.innerHTML = '.post-tags { display:none !important } .article-cta a { font-size: 18px; }'; document.body.appendChild(css); //Extra //This function adds some accessibility needs to the site. function addAlly() { // In this function JQuery is replaced with vanilla javascript functions const imgCont = document.querySelector('.uw-imgcont'); imgCont.setAttribute('aria-label', 'AI news, latest developments'); imgCont.title = 'AI news, latest developments'; imgCont.rel = 'noopener'; document.querySelector('.page-mobile-menu-logo a').title = 'Towards AI Home'; document.querySelector('a.social-link').rel = 'noopener'; document.querySelector('a.uw-text').rel = 'noopener'; document.querySelector('a.uw-w-branding').rel = 'noopener'; document.querySelector('.blog h2.heading').innerHTML = 'Publication'; const popupSearch = document.querySelector$('a.btn-open-popup-search'); popupSearch.setAttribute('role', 'button'); popupSearch.title = 'Search'; const searchClose = document.querySelector('a.popup-search-close'); searchClose.setAttribute('role', 'button'); searchClose.title = 'Close search page'; // document // .querySelector('a.btn-open-popup-search') // .setAttribute( // 'href', // 'https://medium.com/towards-artificial-intelligence/search' // ); } // Add external attributes to 302 sticky and editorial links function extLink() { // Sticky 302 links, this fuction opens the link we send to Medium on a new tab and adds a "noopener" rel to them var stickyLinks = document.querySelectorAll('.grid-item.sticky a'); for (var i = 0; i < stickyLinks.length; i++) { /* stickyLinks[i].setAttribute('target', '_blank'); stickyLinks[i].setAttribute('rel', 'noopener'); */ } // Editorial 302 links, same here var editLinks = document.querySelectorAll( '.grid-item.category-editorial a' ); for (var i = 0; i < editLinks.length; i++) { editLinks[i].setAttribute('target', '_blank'); editLinks[i].setAttribute('rel', 'noopener'); } } // Add current year to copyright notices document.getElementById( 'js-current-year' ).textContent = new Date().getFullYear(); // Call functions after page load extLink(); //addAlly(); setTimeout(function() { //addAlly(); //ideally we should only need to run it once ↑ }, 5000); }; function closeCookieDialog (){ document.getElementById("cookie-consent").style.display = "none"; return false; } setTimeout ( function () { closeCookieDialog(); }, 15000); console.log(`%c 🚀🚀🚀 ███ █████ ███████ █████████ ███████████ █████████████ ███████████████ ███████ ███████ ███████ ┌───────────────────────────────────────────────────────────────────┐ │ │ │ Towards AI is looking for contributors! │ │ Join us in creating awesome AI content. │ │ Let's build the future of AI together → │ │ https://towardsai.net/contribute │ │ │ └───────────────────────────────────────────────────────────────────┘ `, `background: ; color: #00adff; font-size: large`); //Remove latest category across site document.querySelectorAll('a[rel="category tag"]').forEach(function(el) { if (el.textContent.trim() === 'Latest') { // Remove the two consecutive spaces (  ) if (el.nextSibling && el.nextSibling.nodeValue.includes('\u00A0\u00A0')) { el.nextSibling.nodeValue = ''; // Remove the spaces } el.style.display = 'none'; // Hide the element } }); // Add cross-domain measurement, anonymize IPs 'use strict'; //var ga = gtag; ga('config', 'G-9D3HKKFV1Q', 'auto', { /*'allowLinker': true,*/ 'anonymize_ip': true/*, 'linker': { 'domains': [ 'medium.com/towards-artificial-intelligence', 'datasets.towardsai.net', 'rss.towardsai.net', 'feed.towardsai.net', 'contribute.towardsai.net', 'members.towardsai.net', 'pub.towardsai.net', 'news.towardsai.net' ] } */ }); ga('send', 'pageview'); -->