Find all buttons without a type attribute

Some browsers (like Chrome) will display an error in the console if you have forms created with the form tag and buttons without the type attribute. So it can be useful to have a script that find all these buttons so you can add them the type attribute. The good news is that with Python and BeautifulSoup 4 it is really easy:

import glob

from bs4 import BeautifulSoup


def fix_buttons_type():
    for html_file_path in glob.glob('**/*.html', recursive=True):
        with open(html_file_path, 'r') as html_file:
            soup = BeautifulSoup(html_file.read(), 'html.parser')
            number_buttons_without_type = 0
            buttons = soup.find_all('button')
            for button in buttons:
                if button.get('type') is None:
                    if number_buttons_without_type == 0:
                        print(html_file_path, end=' ')
                    number_buttons_without_type += 1

            if number_buttons_without_type > 0:
                print(number_buttons_without_type)


if __name__ == '__main__':
    fix_buttons_type()

Note: If you are using Python 3.4 or below, replace import glob by import glob2 as glob and install glob2.

It is possible to slightly modify the script to add the type attribute with a default value like this type="button". This signals the browser that the buttons is not related to the form (submission or reset). The problem is: this may break the formating of you file.

import glob

from bs4 import BeautifulSoup


def fix_buttons_type():
    for html_file_path in glob.glob('**/*.html', recursive=True):
        with open(html_file_path, 'r') as html_file:
            soup = BeautifulSoup(html_file.read(), 'html.parser')
            number_buttons_without_type = 0
            buttons = soup.find_all('button')
            for button in buttons:
                if button.get('type') is None:
                    button['type'] = 'button'

        with open(html_file_path, 'w') as html_file:
            html_file.write(soup.prettify())


if __name__ == '__main__':
    fix_buttons_type()

Pages

blogroll

social