### Example Output 1 Source: https://github.com/alir3z4/html2text/blob/master/test/backquote_code_style.html This snippet shows a sample output from the conversion process, representing a list of items. ```text a b c ``` -------------------------------- ### Clone and Install html2text Source: https://github.com/alir3z4/html2text/blob/master/docs/usage.md Clone the html2text repository from GitHub, build the package, and install it using pip. ```bash $ git clone --depth 50 https://github.com/Alir3z4/html2text.git $ python -m build -nwx $ python -m pip install --upgrade ./dist/*.whl ``` -------------------------------- ### Install html2text using pip Source: https://github.com/alir3z4/html2text/blob/master/README.md Standard command to install the html2text package from PyPI using pip. Ensure you have pip installed and configured. ```shell $ pip install html2text ``` -------------------------------- ### Example Output 2 Source: https://github.com/alir3z4/html2text/blob/master/test/backquote_code_style.html This snippet shows another sample output from the conversion process, representing a different list of items. ```text d e f ``` -------------------------------- ### Show html2text Version via CLI Source: https://context7.com/alir3z4/html2text/llms.txt Display the installed version of the `html2text` package by running `html2text --version` from the command line. ```bash html2text --version ``` -------------------------------- ### Python Function Example Source: https://github.com/alir3z4/html2text/blob/master/test/normal_escape_snob.md A basic Python function that returns 'a' if the input is less than 1, otherwise returns 'b'. ```python def func(x): if x < 1: return 'a' return 'b' ``` -------------------------------- ### Empty Hyperlink Markdown Source: https://github.com/alir3z4/html2text/blob/master/test/empty-link.html This example shows an empty hyperlink in markdown format. It is used to test how such links are rendered or ignored by markdown processors. ```markdown [](http://some.link) ``` -------------------------------- ### Nested Code Block Example 2 Source: https://github.com/alir3z4/html2text/blob/master/test/mixed_nested_lists.md Illustrates a code block nested deeper within a structure of mixed ordered and unordered lists. ```text d e f ``` -------------------------------- ### JavaScript CDATA Example Source: https://github.com/alir3z4/html2text/blob/master/test/normal.html This JavaScript code snippet is wrapped in CDATA to prevent XML parsing issues. It dynamically includes a script from a remote URL. ```javascript //'); })("test"); //]]> ``` -------------------------------- ### Nested Code Block Example 1 Source: https://github.com/alir3z4/html2text/blob/master/test/mixed_nested_lists.md Represents a code block nested within an unordered list, which is itself nested within another unordered list. ```text a b c ``` -------------------------------- ### Incremental HTML Feeding with HTML2Text.feed() Source: https://context7.com/alir3z4/html2text/llms.txt Feeds HTML incrementally without producing output, suitable for streaming or chunk-based processing. Use `finish()` to get the final Markdown. Script tags are sanitized before feeding. ```python import html2text h = html2text.HTML2Text() h.body_width = 0 chunks = [ "", "

Streaming

", "

This content is fed incrementally.

", "", ] for chunk in chunks: h.feed(chunk) h.feed("") # flush markdown = h.optwrap(h.finish()) print(markdown) ``` -------------------------------- ### Python Conditional String Return Source: https://github.com/alir3z4/html2text/blob/master/test/GoogleDocSaved.html A Python function that returns 'a' if the input is less than 1, otherwise returns 'b'. This is a simple example of conditional logic. ```python def func(x): if x < 1: return 'a' return 'b' ``` -------------------------------- ### Convert HTML to Markdown in Python Source: https://github.com/alir3z4/html2text/blob/master/README.md Basic usage of the html2text library to convert an HTML string to Markdown text. No special setup is required beyond importing the library. ```python >>> import html2text >>> >>> print(html2text.html2text("

Zed's dead baby, Zed's dead.

")) **Zed's** dead baby, _Zed's_ dead. ``` -------------------------------- ### Default Inline Link Handling Source: https://context7.com/alir3z4/html2text/llms.txt Demonstrates the default behavior of handling links, where identical link text and href result in automatic link detection. ```python import html2text # Default: inline links h = html2text.HTML2Text() print(h.handle('

See https://example.com.

')) ``` -------------------------------- ### Handle Lists in HTML Source: https://context7.com/alir3z4/html2text/llms.txt Demonstrates how to convert HTML unordered and ordered lists to Markdown. The list item marker can be customized. ```python print(h.handle("")) ``` ```python h.ul_item_mark = "-" # use dash instead of asterisk print(h.handle("")) ``` ```python print(h.handle("
  1. First
    1. Sub A
    2. Sub B
  2. Second
")) ``` -------------------------------- ### Run Pre-Commit Hooks with tox Source: https://github.com/alir3z4/html2text/blob/master/README.md Command to run pre-commit checks, including linting with mypy, Flake8, and Black, using tox. This ensures code quality before committing. ```shell $ tox -e pre-commit ``` -------------------------------- ### Run html2text as a Python Module Source: https://context7.com/alir3z4/html2text/llms.txt Execute the `html2text` package as a Python module using `python -m html2text` followed by the HTML filename for conversion. ```bash python -m html2text page.html ``` -------------------------------- ### Default Body Width and Wrapping Source: https://context7.com/alir3z4/html2text/llms.txt Demonstrates the default line wrapping behavior at 78 characters per line for Markdown output. ```python import html2text h = html2text.HTML2Text() # Default wrapping at 78 characters h.body_width = 78 long = "

" + ("word " * 30) + "

" print(h.handle(long)) ``` -------------------------------- ### Run Unit Tests with tox Source: https://github.com/alir3z4/html2text/blob/master/README.md Command to execute the project's unit tests using the tox testing tool. This is useful for verifying code integrity during development. ```shell $ tox ``` -------------------------------- ### HTML2Text Class - Table Handling Options Source: https://context7.com/alir3z4/html2text/llms.txt Manage table conversion using `bypass_tables`, `ignore_tables`, and `pad_tables`. `bypass_tables = True` passes tables through as raw HTML. `ignore_tables = True` strips table tags but keeps text rows. ```python import html2text table_html = """
NameScore
Alice95
Bob87
""" h2 = html2text.HTML2Text() print(h2.handle(table_html)) # Output: # Name | Score # --- | --- # Alice | 95 # Bob | 87 h2.bypass_tables = True # emit tables as raw HTML print(h2.handle(table_html)) # Output: ...
passthrough h2.bypass_tables = False h2.ignore_tables = True # strip table tags, keep text rows print(h2.handle(table_html)) # Output: Name Score #Alice 95 #Bob 87 h2.ignore_tables = False h2.pad_tables = True # pad cells to equal column widths print(h2.handle(table_html)) # Output: padded Markdown table aligned to column widths ``` -------------------------------- ### Batch Convert HTML Directory to Markdown Source: https://context7.com/alir3z4/html2text/llms.txt Recursively finds all HTML files in a specified directory, converts them to Markdown, and saves them in a corresponding output directory. Ensures output directories are created as needed. ```python import os import glob def batch_convert(html_dir: str, md_dir: str) -> None: """Batch convert HTML files in a directory to Markdown.""" os.makedirs(md_dir, exist_ok=True) h = html2text.HTML2Text() h.body_width = 0 h.backquote_code_style = True h.ignore_images = False h.pad_tables = True for html_file in glob.glob(os.path.join(html_dir, "**/*.html"), recursive=True): rel = os.path.relpath(html_file, html_dir) md_file = os.path.join(md_dir, rel.replace(".html", ".md")) os.makedirs(os.path.dirname(md_file), exist_ok=True) with open(html_file, "r", encoding="utf-8", errors="replace") as f: content = f.read() with open(md_file, "w", encoding="utf-8") as f: f.write(h.handle(content)) print(f"Converted: {html_file} → {md_file}") batch_convert("site/html", "site/markdown") ``` -------------------------------- ### HTML2Text Class - Link Handling Options Source: https://context7.com/alir3z4/html2text/llms.txt Configure link handling by setting instance attributes like `ignore_links`, `inline_links`, and `protect_links`. `inline_links = False` uses reference-style links, while `protect_links = True` wraps URLs in angle brackets. ```python import html2text h = html2text.HTML2Text() # --- Link handling --- h.ignore_links = True print(h.handle('

Visit our site.

')) # Output: Visit our site. h.ignore_links = False h.inline_links = False # use reference-style links print(h.handle('

See here.

')) # Output: # See [here][1]. # [1]: https://example.com "Home" h.inline_links = True # restore inline links h.protect_links = True # wrap URLs in angle brackets to prevent line-break issues print(h.handle('link')) # Output: [link]() ``` -------------------------------- ### Configure html2text to Ignore Links Source: https://github.com/alir3z4/html2text/blob/master/README.md Demonstrates how to instantiate the HTML2Text class and configure it to ignore HTML links. This prevents link formatting from appearing in the output. ```python >>> import html2text >>> >>> h = html2text.HTML2Text() >>> # Ignore converting links from HTML >>> h.ignore_links = True >>> print(h.handle("

Hello, world!")) Hello, world! ``` -------------------------------- ### Escaped Backslashes and Paths Source: https://github.com/alir3z4/html2text/blob/master/test/normal_escape_snob.html Illustrates how Windows and UNC paths with backslashes are represented, including escaped characters. ```text c:\tmp, \\server\path, \_/, foo\bar, #\#, \\# ``` -------------------------------- ### Customizing html2text Options Source: https://github.com/alir3z4/html2text/blob/master/docs/usage.md Instantiate HTML2Text and modify its attributes to customize the conversion process before handling HTML content. ```python import html2text text_maker = html2text.HTML2Text() text_maker.ignore_links = True text_maker.bypass_tables = False html = function_to_get_some_html() text = text_maker.handle(html) print(text) ``` -------------------------------- ### Use Reference-Style Links with html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Employ the `--reference-links` flag with the `html2text` command-line tool to format links in Markdown using the reference-style convention. ```bash html2text --reference-links page.html ``` -------------------------------- ### Generate HTML Coverage Report Source: https://github.com/alir3z4/html2text/blob/master/README.md Command to generate an HTML report of code coverage using the 'coverage' tool. Open the generated index.html file in a browser to view results. ```shell $ coverage html ``` -------------------------------- ### Pad Table Cells with html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Employ the `--pad-tables` flag to ensure that table cells are padded to equal widths by the `html2text` command-line tool, improving table alignment in Markdown. ```bash html2text --pad-tables page.html ``` -------------------------------- ### Render Ordered List Items Source: https://github.com/alir3z4/html2text/blob/master/test/mixed_nested_lists.html This snippet shows how ordered list items are rendered. Each item is presented on a new line. ```text 1. ordered 2. ... * unordered * ... 4. end * unordered * ... 1. ordered 2. ... * end * unordered * ... 1. ordered 2. code: a b c 3. ... 1. ordered 2. code: d e f 3. ... 5. end * end ``` -------------------------------- ### HTML2Text Class - Image Handling Options Source: https://context7.com/alir3z4/html2text/llms.txt Control image conversion with `ignore_images`, `images_to_alt`, and `images_with_size`. Set `images_to_alt = True` to discard `src` and keep only `alt` text. `images_with_size = True` emits raw `` tags when width/height are present. ```python import html2text h = html2text.HTML2Text() # --- Image handling --- h.ignore_images = True print(h.handle('A photo')) # Output: (empty) h.ignore_images = False h.images_to_alt = True # discard src, keep only alt text print(h.handle('A photo')) # Output: A photo h.images_to_alt = False h.images_with_size = True # emit raw when width/height present print(h.handle('photo')) # Output: photo h.images_with_size = False h.images_as_html = True # always emit raw print(h.handle('Logo')) # Output: Logo h.images_as_html = False ``` -------------------------------- ### Basic Python Function Source: https://github.com/alir3z4/html2text/blob/master/test/mark_code.md A simple Python function definition. This snippet demonstrates basic Python syntax. ```python import os def function(): a = 1 ``` -------------------------------- ### Sample Code Block 1 Source: https://github.com/alir3z4/html2text/blob/master/test/backquote_code_style.md A basic code block with three lines of content. ```text a b c ``` -------------------------------- ### Configure html2text to Process Links Source: https://github.com/alir3z4/html2text/blob/master/README.md Shows how to re-enable link processing after it has been disabled. This will include links in the Markdown output using reference-style formatting. ```python >>> # Don't Ignore links anymore, I like links >>> h.ignore_links = False >>> print(h.handle("

Hello, world!")) Hello, [world](https://www.google.com/earth/)! ``` -------------------------------- ### Custom Quotation Marks for Tag Source: https://context7.com/alir3z4/html2text/llms.txt Allows setting custom opening and closing quotation marks for the HTML q tag. ```python h4 = html2text.HTML2Text() h4.open_quote = "«" h4.close_quote = "»" print(h4.handle("

He said hello.

")) ``` -------------------------------- ### Fenced Code Blocks with html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Use the `--backquote-code-style` flag with the `html2text` command-line tool to render code blocks using triple-backtick Markdown fencing. ```bash html2text --backquote-code-style page.html ``` -------------------------------- ### Basic HTML and CSS Styling Source: https://github.com/alir3z4/html2text/blob/master/test/GoogleDocSaved.html Defines basic HTML element styles and layout properties for a document. Includes styles for lists, paragraphs, and specific classes for layout and appearance. ```css ol{margin:0;padding:0}p{margin:0}.c12{list-style-type:disc;margin:0;padding:0;text-decoration:none;}.c8{width:468pt;background-color:#ffffff;padding:72pt 72pt 72pt 72pt}.c2{padding-left:0pt;direction:ltr;margin-left:36pt}.c11{list-style-type:lower-latin;margin:0;padding:0}.c4{list-style-type:circle;margin:0;padding:0}.c1{padding-left:0pt;direction:ltr;margin-left:72pt}.c7{;margin:0;padding:0}.c3{font-style:italic;font-family:Courier New}.c0{height:11pt;direction:ltr}.c5{font-weight:bold}.c9{font-family:Consolas}.c13{font-family:Courier New}.c6{direction:ltr}.c10{font-style:italic}body{color:#000000;font-size:11pt;font-family:Arial}h1{padding-top:24pt;color:#000000;font-size:24pt;font-family:Arial;font-weight:bold;padding-bottom:6pt}h2{padding-top:18pt;color:#000000;font-size:18pt;font-family:Arial;font-weight:bold;padding-bottom:4pt}h3{padding-top:14pt;color:#000000;font-size:14pt;font-family:Arial;font-weight:bold;padding-bottom:4pt}h4{padding-top:12pt;color:#000000;font-size:12pt;font-family:Arial;font-weight:bold;padding-bottom:2pt}h5{padding-top:11pt;color:#000000;font-size:11pt;font-family:Arial;font-weight:bold;padding-bottom:2pt}h6{padding-top:10pt;color:#000000;font-size:10pt;font-family:Arial;font-weight:bold;padding-bottom:2pt} ``` -------------------------------- ### Convert HTML File to Markdown using html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt The `html2text` command-line tool converts HTML files or stdin to Markdown. Basic usage involves providing the HTML filename as an argument. ```bash html2text page.html ``` -------------------------------- ### Legacy [code] Marker Style for Code Blocks Source: https://context7.com/alir3z4/html2text/llms.txt Set `mark_code = True` to use the legacy `[code]...[/code]` markers for rendering `
` blocks. This is an alternative to standard Markdown formatting. Ensure `body_width=0`.

```python
h3 = html2text.HTML2Text()
h3.body_width = 0
h3.mark_code = True
print(h3.handle(code_html))
```

--------------------------------

### HTML2Text Class

Source: https://context7.com/alir3z4/html2text/llms.txt

The main parser class, a subclass of `html.parser.HTMLParser`. Instantiate once, configure attributes, then call `.handle()` repeatedly for multiple documents. Supports all conversion options as instance attributes.

```APIDOC
## HTML2Text Class

### Description
A configurable HTML-to-Markdown converter that inherits from `html.parser.HTMLParser`. It allows fine-grained control over the conversion process through instance attributes.

### Instantiation
```python
import html2text

h = html2text.HTML2Text()
```

### Attributes (Configuration Options)
- **ignore_links** (boolean) - If True, ignore all links.
- **inline_links** (boolean) - If True, use inline-style links. If False, use reference-style links.
- **protect_links** (boolean) - If True, wrap URLs in angle brackets to prevent line-break issues.
- **ignore_images** (boolean) - If True, ignore all images.
- **images_to_alt** (boolean) - If True, discard image `src` and keep only `alt` text.
- **images_with_size** (boolean) - If True, emit raw `` tags when width/height attributes are present.
- **images_as_html** (boolean) - If True, always emit raw `` tags.
- **bypass_tables** (boolean) - If True, emit tables as raw HTML.
- **ignore_tables** (boolean) - If True, strip table tags but keep text rows.
- **pad_tables** (boolean) - If True, pad table cells to equal column widths.
- **body_width** (integer) - Controls line-wrapping for the output. Set to 0 for no wrapping.

### Method
#### handle(html_string)

Parses an HTML string and returns the converted Markdown string. Resets internal state on each call, making the instance safely reusable.

### Request Example (Link Handling)
```python
h = html2text.HTML2Text()
h.ignore_links = False
h.inline_links = False
print(h.handle('

See here.

')) ``` ### Response Example (Link Handling) ``` See [here][1]. [1]: https://example.com "Home" ``` ### Request Example (Image Handling) ```python h = html2text.HTML2Text() h.ignore_images = False h.images_to_alt = True print(h.handle('A photo')) ``` ### Response Example (Image Handling) ``` A photo ``` ### Request Example (Table Handling) ```python table_html = """
NameScore
Alice95
Bob87
""" h2 = html2text.HTML2Text() print(h2.handle(table_html)) ``` ### Response Example (Table Handling) ``` Name | Score --- | --- Alice | 95 Bob | 87 ``` ``` -------------------------------- ### Convert HTML File to Markdown Source: https://context7.com/alir3z4/html2text/llms.txt Reads an HTML file, converts its content to Markdown, and writes the output to a new file. Includes error handling for Unicode decoding issues and allows configuration of various conversion options. ```python import html2text def convert_file(input_path: str, output_path: str, **options) -> None: """Convert an HTML file to a Markdown file with configurable options.""" with open(input_path, "rb") as f: raw = f.read() try: html_content = raw.decode("utf-8") except UnicodeDecodeError: html_content = raw.decode("utf-8", errors="replace") h = html2text.HTML2Text() h.body_width = options.get("body_width", 0) h.ignore_links = options.get("ignore_links", False) h.ignore_images = options.get("ignore_images", False) h.backquote_code_style = options.get("backquote_code_style", True) h.pad_tables = options.get("pad_tables", True) h.unicode_snob = options.get("unicode_snob", True) markdown = h.handle(html_content) with open(output_path, "w", encoding="utf-8") as f: f.write(markdown) # Usage convert_file( "docs/index.html", "docs/index.md", body_width=0, backquote_code_style=True, pad_tables=True, ) ``` -------------------------------- ### Google Docs Export with Strikethrough Hiding via CLI Source: https://context7.com/alir3z4/html2text/llms.txt Combine `--google-doc` and `--hide-strikethrough` flags in the `html2text` command-line tool to process Google Docs exports while omitting strikethrough text. ```bash html2text --google-doc --hide-strikethrough export.html ``` -------------------------------- ### Sample Code Block 2 Source: https://github.com/alir3z4/html2text/blob/master/test/backquote_code_style.md Another code block with three lines of content, following a different structure. ```text d e f ``` -------------------------------- ### Convert HTML with Specific Encoding using html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Specify the encoding of the HTML file when converting using the `html2text` command-line tool by providing the encoding name as a second argument. ```bash html2text page.html latin-1 ``` -------------------------------- ### Handle Superscript and Subscript in HTML Source: https://context7.com/alir3z4/html2text/llms.txt Converts HTML sup and sub tags to their Markdown equivalents when `include_sup_sub` is enabled. This is useful for scientific notation or chemical formulas. ```python h.include_sup_sub = True print(h.handle("

H2O and E=mc2

")) ``` -------------------------------- ### Handle Blockquotes in HTML Source: https://context7.com/alir3z4/html2text/llms.txt Converts HTML blockquote tags to Markdown blockquotes. Ensure the content within the blockquote is properly formatted. ```python print(h.handle("

To be or not to be.

")) ``` -------------------------------- ### Bypass Tables with html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Use the `--bypass-tables` flag to have the `html2text` command-line tool pass through HTML table structures directly without converting them to Markdown. ```bash html2text --bypass-tables page.html ``` -------------------------------- ### Handle Code Blocks in HTML Source: https://context7.com/alir3z4/html2text/llms.txt Converts HTML pre and code tags to Markdown code blocks. Setting `backquote_code_style` to True enables backtick style code blocks. ```python h.backquote_code_style = True print(h.handle("
def hello():
    print('hi')
")) ``` -------------------------------- ### HTML2Text.handle() - Heading Conversion Source: https://context7.com/alir3z4/html2text/llms.txt Use the `.handle()` method of an `HTML2Text` instance to parse HTML strings and convert them to Markdown. Set `body_width = 0` to disable line wrapping for headings. ```python import html2text h = html2text.HTML2Text() h.body_width = 0 # no line wrapping # Headings print(h.handle("

Title

Subtitle

Section

")) # Output: # # Title # ## Subtitle # ## Section ``` -------------------------------- ### Default Code Block Formatting (Indent-based) Source: https://context7.com/alir3z4/html2text/llms.txt The default behavior for `
` blocks is to indent the content by 4 spaces. Set `body_width=0` to ensure proper rendering without line wrapping.

```python
import html2text

code_html = """

def greet(name):
    return f"Hello, {name}!"

print(greet("world"))
""" # Default: indent-based code block (4 spaces) h = html2text.HTML2Text() h.body_width = 0 print(h.handle(code_html)) ``` -------------------------------- ### Read HTML from Stdin using html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Pipe HTML content to the `html2text` command-line tool via standard input to convert it to Markdown. This is useful for processing output from other commands or network requests. ```bash curl -s https://example.com | html2text ``` -------------------------------- ### Import Google Font CSS Source: https://github.com/alir3z4/html2text/blob/master/test/GoogleDocSaved.html Imports a Google Font stylesheet using @import. Ensure this is placed at the top of your CSS. ```css @import url('https://themes.googleusercontent.com/fonts/css?kit=lhDjYqiy3mZ0x6ROQEUoUw'); ``` -------------------------------- ### Handle Encoding Errors Gracefully with html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Use `--decode-errors=ignore` with the `html2text` command-line tool to gracefully handle character encoding errors during conversion, preventing failures. ```bash html2text --decode-errors=ignore page.html ``` -------------------------------- ### Default Emphasis and Typography Source: https://context7.com/alir3z4/html2text/llms.txt Shows the default Markdown output for emphasis (italic with underscore, bold with double asterisk). ```python import html2text h = html2text.HTML2Text() # Default: underscore for em, ** for strong print(h.handle("

italic and bold

")) ``` -------------------------------- ### Custom List and Emphasis Characters with html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Use `-d` for dashes in unordered lists and `-e` for asterisks in emphasis with the `html2text` command-line tool to customize Markdown formatting. ```bash html2text -d -e page.html ``` -------------------------------- ### Handle Escaped HTML in PRE tags Source: https://github.com/alir3z4/html2text/blob/master/test/html-escaping.html Verifies that even when escaped HTML is placed inside a <pre> tag, it is still unescaped in the final text output. ```html
<div>
``` -------------------------------- ### Custom Quote Characters with html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Specify custom opening and closing quote characters using `--open-quote` and `--close-quote` flags with the `html2text` command-line tool for localized output. ```bash html2text --open-quote="«" --close-quote="»" page.html ``` -------------------------------- ### Custom Emphasis Marks Source: https://context7.com/alir3z4/html2text/llms.txt Allows customization of emphasis marks, switching between asterisks for italic and double underscores for bold. ```python h.emphasis_mark = "*" h.strong_mark = "__" print(h.handle("

italic and bold

")) ``` -------------------------------- ### Handle Inline Code in HTML Source: https://context7.com/alir3z4/html2text/llms.txt Converts HTML code tags within paragraphs to inline Markdown code. This is useful for highlighting code snippets or function names. ```python print(h.handle("

Use the print() function.

")) ``` -------------------------------- ### Basic CSS Rule Source: https://github.com/alir3z4/html2text/blob/master/test/normal_escape_snob.html Shows a simple CSS rule. This is typically stripped out or represented as plain text. ```css Normal #example { color: red; } ``` -------------------------------- ### Include Internal Anchors Source: https://context7.com/alir3z4/html2text/llms.txt Includes internal anchors (fragment links) in the Markdown output by setting `skip_internal_links` to False. ```python h.skip_internal_links = False print(h.handle('Jump to section 2')) ``` -------------------------------- ### Handle Escaped HTML in CODE tags Source: https://github.com/alir3z4/html2text/blob/master/test/html-escaping.html Confirms that escaped HTML within a <code> tag is also unescaped in the resulting text. ```html & ``` -------------------------------- ### Escape All Special Characters with html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Use the `--escape-all` flag with the `html2text` command-line tool to escape all special Markdown characters, ensuring maximum compatibility at the cost of readability. ```bash html2text --escape-all page.html ``` -------------------------------- ### html2text.html2text() - Basic HTML to Markdown Conversion Source: https://context7.com/alir3z4/html2text/llms.txt Use this function for simple, one-off HTML to Markdown conversions. It accepts an optional `baseurl` for resolving relative links and `bodywidth` for line wrapping. ```python import html2text # Basic conversion result = html2text.html2text("

Hello, world!

") print(result) # Output: **Hello**, _world_! # With baseurl to resolve relative links html = 'About | Contact' result = html2text.html2text(html, baseurl="https://example.com") print(result) # Output: [About](https://example.com/about) | [Contact](https://example.com/contact) # Disable line wrapping long_html = "

" + ("This is a very long paragraph with lots of text. " * 5) + "

" result = html2text.html2text(long_html, bodywidth=0) print(result) # Output: single unwrapped line ``` -------------------------------- ### Triple Backquote Fenced Code Block Style Source: https://context7.com/alir3z4/html2text/llms.txt Enable `backquote_code_style = True` to render `
` blocks using standard triple-backtick Markdown fencing. Ensure `body_width=0` for correct formatting.

```python
h2 = html2text.HTML2Text()
h2.body_width = 0
h2.backquote_code_style = True
print(h2.handle(code_html))
```

--------------------------------

### Handle Strikethrough in HTML

Source: https://context7.com/alir3z4/html2text/llms.txt

Converts HTML del tags to Markdown strikethrough. This is used to indicate deleted or struck-through text.

```python
print(h.handle("

old price new price

")) ``` -------------------------------- ### No Line Wrapping Source: https://context7.com/alir3z4/html2text/llms.txt Disables line wrapping entirely by setting `body_width` to 0, causing the entire paragraph to appear on a single line. ```python h.body_width = 0 print(h.handle(long)) ``` -------------------------------- ### Disable Link Output with html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Use the `--ignore-links` flag with the `html2text` command-line tool to exclude hyperlink URLs from the Markdown output. ```bash html2text --ignore-links page.html ``` -------------------------------- ### No Line Wrapping with html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Set `--body-width=0` to disable line wrapping in the `html2text` command-line tool, ensuring that lines are not broken and maintain their original length. ```bash html2text --body-width=0 page.html ``` -------------------------------- ### Google Docs Export Conversion in html2text Source: https://context7.com/alir3z4/html2text/llms.txt Enable `google_doc = True` for special handling of HTML exported from Google Docs. This mode interprets inline CSS styles for formatting like bold, italic, and code. ```python import html2text h = html2text.HTML2Text() h.google_doc = True google_doc_html = """

Project Overview

Updated quarterly

run_pipeline()

""" print(h.handle(google_doc_html)) ``` -------------------------------- ### Preserve HTML Entities in Text Conversion Source: https://github.com/alir3z4/html2text/blob/master/test/html-escaping.html Ensures that HTML entities like '&' are correctly converted to their plain text representation and not retained in their escaped form. ```html & ``` -------------------------------- ### Enable List Item Wrapping in html2text Source: https://context7.com/alir3z4/html2text/llms.txt Set `wrap_list_items` to `True` to enable wrapping of list items. This option is disabled by default and affects how long list content is formatted. ```python h3 = html2text.HTML2Text() h3.body_width = 40 h3.wrap_list_items = True print(h3.handle("
  • " + ("word " * 20) + "
")) ``` -------------------------------- ### Disable Image Output with html2text CLI Source: https://context7.com/alir3z4/html2text/llms.txt Use the `--ignore-images` flag with the `html2text` command-line tool to exclude image references from the Markdown output. ```bash html2text --ignore-images page.html ``` -------------------------------- ### html2text.html2text() Source: https://context7.com/alir3z4/html2text/llms.txt The top-level convenience function for converting an HTML string to Markdown text in a single call. It accepts an optional `baseurl` to resolve relative links and an optional `bodywidth` to control line-wrapping. ```APIDOC ## html2text.html2text() ### Description Converts an HTML string to Markdown text in a single call. ### Parameters - **html** (string) - Required - The HTML string to convert. - **baseurl** (string) - Optional - A base URL to resolve relative links. - **bodywidth** (integer) - Optional - Controls line-wrapping. Set to 0 for no wrapping. ### Returns - **string** - The converted Markdown string. ### Request Example ```python import html2text result = html2text.html2text("

Hello, world!

") print(result) ``` ### Response Example ``` **Hello**, _world_! ``` ``` -------------------------------- ### Link References After Each Paragraph Source: https://context7.com/alir3z4/html2text/llms.txt Places link references immediately after each paragraph instead of at the end of the document by setting `inline_links` to False and `links_each_paragraph` to True. ```python h2 = html2text.HTML2Text() h2.inline_links = False h2.links_each_paragraph = True html = "

See site A and site B.

" print(h2.handle(html)) ``` -------------------------------- ### Preserve HTML Tags in Text Conversion Source: https://github.com/alir3z4/html2text/blob/master/test/html-escaping.html Ensures that HTML tags within the content are not preserved as escaped characters in the output. ```html
``` -------------------------------- ### Python Function Definition Source: https://github.com/alir3z4/html2text/blob/master/test/GoogleDocSaved.md A basic Python function that returns 'a' if the input is less than 1, otherwise returns 'b'. ```python def func(x): if x < 1: return 'a' return 'b' ``` -------------------------------- ### Ignore Mailto Links Source: https://context7.com/alir3z4/html2text/llms.txt Ignores mailto links, rendering them as plain text by setting `ignore_mailto_links` to True. ```python h3 = html2text.HTML2Text() h3.ignore_mailto_links = True print(h3.handle('Email us')) ``` -------------------------------- ### Unicode vs ASCII Entity Handling Source: https://context7.com/alir3z4/html2text/llms.txt Controls whether Unicode characters or ASCII entities are used for special characters. Set `unicode_snob` to True for Unicode. ```python h3 = html2text.HTML2Text() h3.unicode_snob = True # use real Unicode chars (e.g. — instead of --) print(h3.handle("

dash—here © 2024

")) ``` ```python h3.unicode_snob = False print(h3.handle("

dash—here © 2024

")) ``` -------------------------------- ### Single Line Break Mode in html2text Source: https://context7.com/alir3z4/html2text/llms.txt Configure `single_line_break` to `True` when `body_width` is set to `0` to separate paragraphs with a single newline instead of the default two. This provides a more compact output. ```python h4 = html2text.HTML2Text() h4.body_width = 0 h4.single_line_break = True print(h4.handle("

First paragraph.

Second paragraph.

")) ``` -------------------------------- ### Hide Strikethrough Text in Google Docs Exports Source: https://context7.com/alir3z4/html2text/llms.txt Set `hide_strikethrough = True` when using `google_doc = True` to omit text marked with `text-decoration:line-through` from the output. ```python h2 = html2text.HTML2Text() h2.google_doc = True h2.hide_strikethrough = True print(h2.handle('

deleted kept

')) ``` -------------------------------- ### Prevent URL Wrapping in html2text Source: https://context7.com/alir3z4/html2text/llms.txt Set `wrap_links` to `False` to keep URLs on a single line, preventing them from breaking mid-line. This is useful for maintaining the integrity of long URLs. ```python h2 = html2text.HTML2Text() h2.body_width = 40 h2.wrap_links = False # keep links on their own unbroken line html = '

Text before link text after.

' print(h2.handle(html)) ``` -------------------------------- ### Minimal Markdown Escaping in html2text Source: https://context7.com/alir3z4/html2text/llms.txt By default, `html2text` performs minimal escaping of Markdown special characters, only escaping characters necessary for correctness. This balances readability and proper rendering. ```python import html2text h = html2text.HTML2Text() # Default: minimal escaping (only what's necessary for correctness) print(h.handle("

Price: $10 *approx* [see note]

")) ``` -------------------------------- ### Escape All Markdown Special Characters Source: https://context7.com/alir3z4/html2text/llms.txt Set `escape_snob = True` to escape all possible Markdown special characters. This ensures the output is safe for all Markdown parsers but may reduce readability. ```python h.escape_snob = True print(h.handle("

Use #hashtags and _underscores_ freely!

")) ```