Python 3.6中如何打印变量类型且不显示'class'字样?
Got it, let's sort this out! When you run print(type(list(soup.children)[0])), you're printing a list containing a type object, which is why you get the wrapped output [<class 'bs4.element.Tag'>]. To get just the bs4.element.Tag string like you see when directly evaluating type(list(soup.children)[0]) in the command line, here are two reliable approaches:
Option 1: Use Type Attributes (Recommended)
Python's type objects have built-in attributes to access the module and class name directly. This is the most robust method since it doesn't rely on string formatting that might change:
# Get the type object first element_type = type(list(soup.children)[0]) # Combine module and class name for the full path print(f"{element_type.__module__}.{element_type.__name__}")
This will output exactly bs4.element.Tag — perfect for what you need. If you only wanted the short class name (like Tag), you could just use element_type.__name__.
Option 2: String Manipulation
If you prefer a quick hack, you can convert the type object to a string and extract the part you need:
type_string = str(type(list(soup.children)[0])) # Split the string on single quotes and grab the middle segment print(type_string.split("'")[1])
This works because the default string representation of a type is <class 'module.class'>, so splitting on ' gives us a list where the second element is the full class path.
Why Your Original Output Looked Different
When you directly enter type(list(soup.children)[0]) in the command line, Python uses its default repr() output for the type object. But when you wrap it in a list and print the list, you're seeing the repr() of the list containing the type object — hence the extra brackets and full class wrapper text.
内容的提问来源于stack exchange,提问作者Ohad Rozen

