BeautifulSoup reorders HTML tag attributes alphabetically - how to preserve original order? [duplicate]

1 day ago 1
ARTICLE AD BOX

As you stated, the order of attributes in HTML doesn't matter. But if you really want unsorted attributes, you can do:

from bs4 import BeautifulSoup from bs4.formatter import HTMLFormatter class UnsortedAttributes(HTMLFormatter): def attributes(self, tag): yield from tag.attrs.items() tags = BeautifulSoup('<span id="100" class="test"></span>', "html.parser") print(tags.encode(formatter=UnsortedAttributes()).decode())

Prints:

<span id="100" class="test"></span>

EDIT: To not close void tags you can try:

class UnsortedAttributes(HTMLFormatter): def __init__(self): super().__init__( void_element_close_prefix="" ) # <-- use void_element_close_prefix="" here def attributes(self, tag): yield from tag.attrs.items() tags = BeautifulSoup( """<input id="NOT_CLOSED_TAG" type="Button">""", "html.parser", ) print(tags.encode(formatter=UnsortedAttributes()).decode())

Prints:

<input id="NOT_CLOSED_TAG" type="Button">

answered Jul 31, 2023 at 22:26

Andrej Kesely's user avatar

4 Comments

I have something similar which is, if a tag is not closed, beautifulsoup closes it (e.g. <input> becomes <input/>). Is it possible to solve this?

2023-07-31T22:57:36.96Z+00:00

@Minions That's harder problem, because each parser (html.parser, html5lib, lxml) handles this little bit different. I've edited my answer, you can try put void_element_close_prefix="" to the constructor in formatter.

2023-07-31T23:06:26.053Z+00:00

I really appreciate your effort @Andrej! It works actually, but only for the input tag. If I use something like this <span id="100" class="test">, it doesn't work.

2023-07-31T23:13:29.91Z+00:00

@Minions I can only point you how bs4 handles special HTML tags (after all, it's HTML/XML parser): git.launchpad.net/beautifulsoup/tree/bs4/builder/… You can subclass TreeBuilder and use custom empty_element_tags, but this is more work...

2023-07-31T23:17:27.637Z+00:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article