I had a list of URLs in a column in Google Sheets and I wanted to automatically extract their titles. Earlier I thought of using the inbuilt IMPORTXML function, but it’s not reliable, it keeps showing errors.
So I wrote a custom script for Google Sheets that works, here’s the script:
function getTitleOrH1(url) {
var response = UrlFetchApp.fetch(url,
{
method: "get",
muteHttpExceptions: true
});
var html = response.getContentText();
var titleMatch = html.match("<title>(.*?)</title>");
var h1Match = html.match("<h1[^>]*>(.*?)</h1>");
if (titleMatch) {
return titleMatch[1];
} else if (h1Match) {
return h1Match[1];
} else {
return "No title or H1 found";
}
}
Now, I can just call the function by providing the URL reference i.e. getTitleOrH1(A2) and it shows the titles within seconds.
<aside> 💡 It’s going to be extremely helpful while doing programmatic SEO and adding external references from where the pSEO data has been extracted.
</aside>
<aside> 👆 Liked this? Follow me on Twitter for tons of interesting stuff related to SEO, content marketing, business, and productivity.
</aside>