Python Script to Check Title and Meta Description Length

This script checks the basic on-page tags of HTML files: the title length, the meta description length and the number of H1 headings. It uses only the standard library, so you can run it on any computer with Python.

import sys
from html.parser import HTMLParser

class SeoParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.in_title = False
        self.title = ""
        self.description = ""
        self.h1_count = 0

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag == "title":
            self.in_title = True
        elif tag == "meta" and attrs.get("name") == "description":
            self.description = attrs.get("content", "")
        elif tag == "h1":
            self.h1_count += 1

    def handle_endtag(self, tag):
        if tag == "title":
            self.in_title = False

    def handle_data(self, data):
        if self.in_title:
            self.title += data

def check(path):
    parser = SeoParser()
    with open(path, encoding="utf-8") as f:
        parser.feed(f.read())

    print(path)
    print("  Title (%d chars): %s" % (len(parser.title), parser.title))
    print("  Description (%d chars)" % len(parser.description))
    print("  H1 tags: %d" % parser.h1_count)

    if not 30 <= len(parser.title) <= 60:
        print("  WARNING: title should be about 30 to 60 characters")
    if not 70 <= len(parser.description) <= 155:
        print("  WARNING: description should be about 70 to 155 characters")
    if parser.h1_count != 1:
        print("  WARNING: page should have exactly one H1")

for path in sys.argv[1:]:
    check(path)
Output

$ python3 check_seo.py page1.html page2.html
page1.html
Title (40 chars): SEO Title Tag: How to Write a Good Title
Description (92 chars)
H1 tags: 1
page2.html
Title (4 chars): Home
Description (0 chars)
H1 tags: 2
WARNING: title should be about 30 to 60 characters
WARNING: description should be about 70 to 155 characters
WARNING: page should have exactly one H1

How it works

  • HTMLParser reads the HTML and calls a method for each start tag, end tag and text.
  • The class remembers the title text, the content of the description meta tag and counts the H1 tags.
  • The warnings use the common length guidelines. They are a guide, not a strict rule of Google.
  • The first page passes all checks. The second page has a short title, no description and two H1 tags, so the script shows three warnings.
Note: You can extend it to read many files in a folder, or to check canonical tags and image alt text. See Title Tag and Meta Description.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.