bs4 β Beautiful Soup Elixir and Tonic β βThe Screen-Scraperβs Friendβ.
| Use Case | Command | Description |
|---|---|---|
| Parse HTML | soup = BeautifulSoup(html, 'html.parser') | Parse an HTML string into a BeautifulSoup object. |
| Parse XML | soup = BeautifulSoup(xml, 'lxml-xml') | Parse an XML string using lxml. |
| Find all tags | soup.find_all('a') | Find all occurrences of a tag. |
| Find first tag | soup.find('a') | Find the first occurrence of a tag. |
| CSS selector | soup.select('.class') | Select elements by CSS selector. |
| Extract text | soup.get_text() | Get all text from the document. |
| Get attribute | tag['href'] | Get the value of an attribute. |
| Set attribute | tag['href'] = 'new_url' | Set the value of an attribute. |
| Navigate tree | tag.parent | Access the parent of a tag. |
| Iterate children | tag.children | Iterate over direct children. |
| Pretty print | soup.prettify() | Return indented HTML/XML string. |
| Modify tag | new_tag = soup.new_tag('div') | Create a new tag and insert it. |
http://www.crummy.com/software/BeautifulSoup/
Beautiful Soup uses a pluggable XML or HTML parser to parse a (possibly invalid) document into a tree representation. Beautiful Soup provides methods and Pythonic idioms that make it easy to navigate, search, and modify the parse tree.
Beautiful Soup works with Python 3.6 and up. It works better if lxml and/or html5lib is installed.
For more than you ever wanted to know about Beautiful Soup, see the documentation: http://www.crummy.com/software/BeautifulSoup/bs4/doc/
bs4.element.Tag(bs4.element.PageElement)
BeautifulSoup
Constructor: BeautifulSoup(markup='', features=None, builder=None, parse_only=None, from_encoding=None, exclude_encodings=None, element_classes=None, **kwargs)
A data structure representing a parsed HTML or XML document. Most methods are inherited from PageElement or Tag.
__getstate__(self)__init__(self, markup='', features=None, builder=None, parse_only=None, from_encoding=None, exclude_encodings=None, element_classes=None, **kwargs)markup β A string or file-like object representing markup to be parsed.features β Desired parser features (e.g. "lxml", "html.parser", "html5lib") or markup type ("html", "xml").builder β A custom TreeBuilder instance.parse_only β A SoupStrainer to limit parsing to parts of the document.from_encoding β String indicating the document encoding if Beautiful Soup guesses wrongly.exclude_encodings β List of encodings known to be wrong.element_classes β Dictionary mapping BeautifulSoup classes to custom subclasses.**kwargs β Propagated to TreeBuilder constructor; BS3 backwards compatibility args are ignored with a warning.__setstate__(self, state)decode(self, pretty_print=False, eventual_encoding='utf-8', formatter='minimal', iterator=None)pretty_print β If True, indentation is used for readability.eventual_encoding β The encoding of the final document; if None, returns Unicode string.endData(self, containerClass=None)handle_data(self, data)handle_endtag(self, name, nsprefix=None)handle_starttag(self, name, namespace, nsprefix, attrs, sourceline=None, sourcepos=None, namespaces=None)insert_after(self, *args)insert_before(self, *args)new_string(self, s, subclass=None)new_tag(self, name, namespace=None, nsprefix=None, attrs={}, sourceline=None, sourcepos=None, **kwattrs)name β The name of the new Tag.namespace β XML namespace URI.prefix β XML namespace prefix.attrs β Dictionary of attribute values; can be used instead of kwattrs for reserved words like 'class'.object_was_parsed(self, o, parent=None, most_recent_element=None)popTag(self)pushTag(self, tag)reset(self)string_container(self, base_class=None)ASCII_SPACES = ' \n\t\x0c\r'DEFAULT_BUILDER_FEATURES = ['html', 'fast']NO_PARSER_SPECIFIED_WARNING = 'No parser was explicitly specified, so ...'ROOT_TAG_NAME = '[document]'__bool__(self) β A tag is nonβNone even if it has no contents.__call__(self, *args, **kwargs) β Calling a Tag like a function is the same as calling its find_all() method.__contains__(self, x)__copy__(self) β Always a deep copy (children can only have one parent).__deepcopy__(self, memo, recursive=True)__delitem__(self, key) β Deletes all 'key' attributes.__eq__(self, other) β True iff same name, attributes, and contents recursively.__getattr__(self, tag) β Same as tag.find(name="subtag").__getitem__(self, key) β Returns attribute value; raises exception if missing.__hash__(self)__iter__(self) β Iterates over contents.__len__(self) β Length of contents list.__ne__(self, other)__repr__ = __unicode__(self)__setitem__(self, key, value) β Sets attribute value.__str__ = __unicode__(self)__unicode__(self) β Renders as Unicode string.clear(self, decompose=False) β Wipes out all children via extract(); if decompose is True, uses decompose().decode_contents(self, indent_level=None, eventual_encoding='utf-8', formatter='minimal') β Renders contents as Unicode string.decompose(self) β Recursively destroys this element and its children.encode(self, encoding='utf-8', indent_level=None, formatter='minimal', errors='xmlcharrefreplace') β Render as bytestring.encode_contents(self, indent_level=None, encoding='utf-8', formatter='minimal') β Render contents as bytestring.find(self, name=None, attrs={}, recursive=True, string=None, **kwargs) β Find first PageElement matching criteria.find_all(self, name=None, attrs={}, recursive=True, string=None, limit=None, **kwargs) β Find all matching PageElements; returns ResultSet.findAll = find_allfindChild = findfindChildren = find_allget(self, key, default=None) β Returns attribute value or default.get_attribute_list(self, key, default=None) β Same as get() but always returns a list.has_attr(self, key) β Does this element have the attribute?has_key(self, key) β Deprecated.index(self, element) β Find index of a child by identity.prettify(self, encoding=None, formatter='minimal') β Prettyβprint as string.select(self, selector, namespaces=None, limit=None, **kwargs) β Perform CSS selection; returns ResultSet of Tags.select_one(self, selector, namespaces=None, **kwargs) β Perform CSS selection; returns first Tag.smooth(self) β Consolidate consecutive strings.children β Iterate over direct children.css β Interface to CSS selector API.descendants β Iterate over all children breadthβfirst.isSelfClosing β Is this an emptyβelement (selfβclosing) tag?is_empty_element β Same as isSelfClosing.self_and_descendants β Iterate over this element and its children breadthβfirst.strings β Yield all strings (with optional strip and types).parserClassstring β Convenience property to get the single string within this element.DEFAULT_INTERESTING_STRING_TYPESEMPTY_ELEMENT_EVENTEND_ELEMENT_EVENTSTART_ELEMENT_EVENTSTRING_ELEMENT_EVENTappend(self, tag) β Appends a PageElement to contents.extend(self, tags) β Appends a list of PageElements (or a Tag's contents if a single Tag is given).extract(self, _self_index=None) β Destructively removes this element from the tree; returns self.fetchNextSiblings = find_next_siblingsfetchParents = find_parentsfetchPrevious = find_all_previousfetchPreviousSiblings = find_previous_siblingsfindAllNext = find_all_nextfindAllPrevious = find_all_previousfindNext = find_nextfindNextSibling = find_next_siblingfindNextSiblings = find_next_siblingsfindParent = find_parentfindParents = find_parentsfindPrevious = find_previousfindPreviousSibling = find_previous_siblingfindPreviousSiblings = find_previous_siblingsfind_all_next(self, name=None, attrs={}, string=None, limit=None, **kwargs) β Find all matching PageElements later in the document.find_all_previous(self, name=None, attrs={}, string=None, limit=None, **kwargs) β Find all matching PageElements earlier in the document.find_next(self, name=None, attrs={}, string=None, **kwargs) β Find first matching PageElement later in the document.find_next_sibling(self, name=None, attrs={}, string=None, **kwargs) β Find closest later sibling matching criteria.find_next_siblings(self, name=None, attrs={}, string=None, limit=None, **kwargs) β Find all later siblings matching criteria.find_parent(self, name=None, attrs={}, **kwargs) β Find closest parent matching criteria.find_parents(self, name=None, attrs={}, limit=None, **kwargs) β Find all parents matching criteria.find_previous(self, name=None, attrs={}, string=None, **kwargs) β Find first matching PageElement earlier in the document.find_previous_sibling(self, name=None, attrs={}, string=None, **kwargs) β Find closest earlier sibling matching criteria.find_previous_siblings(self, name=None, attrs={}, string=None, limit=None, **kwargs) β Find all earlier siblings matching criteria.format_string(self, s, formatter) β Format string using given formatter.formatter_for_name(self, formatter) β Look up or create a Formatter.getText = get_textget_text(self, separator='', strip=False, types=<object object at 0x7f375cc44cb0>) β Concatenate all child strings using separator.insert(self, position, new_child) β Insert a PageElement at a given position.replaceWith = replace_withreplaceWithChildren = unwrapreplace_with(self, *args) β Replace this element with one or more PageElements.replace_with_children = unwrapsetup(self, parent=None, previous_element=None, next_element=None, previous_sibling=None, next_sibling=None) β Sets initial relations between elements.unwrap(self) β Replace this element with its contents.wrap(self, wrap_inside) β Wrap this element inside another one.decomposed β Check whether element has been decomposed.next β The PageElement parsed just after this one.next_elements β All PageElements parsed after this one.next_siblings β All later siblings.parents β All parents.previous β The PageElement parsed just before this one.previous_elements β All PageElements parsed before this one.previous_siblings β All earlier siblings.stripped_strings β Yield all strings, stripped.text β Get all child strings concatenated (with separator, strip, types).__dict____weakref__nextSiblingpreviousSiblingdefault = <object object>known_xml = None__all__ = ['BeautifulSoup']__copyright__ = 'Copyright (c) 2004-2024 Leonard Richardson'__license__ = 'MIT'4.12.3
Leonard Richardson (leonardr AT segfault.org)
/home/chedong/.local/lib/python3.10/site-packages/bs4/__init__.py
Generated by phpman v4.9.27 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-19 20:28 @216.73.216.114
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format