### 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 //' + 'script>'); })("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 = [ "
", "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("" + ("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 = """| Name | Score |
|---|---|
| Alice | 95 |
| Bob | 87 |
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](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('
'))
# Output: (empty)
h.ignore_images = False
h.images_to_alt = True # discard src, keep only alt text
print(h.handle('
'))
# Output: A photo
h.images_to_alt = False
h.images_with_size = True # emit raw when width/height present
print(h.handle('
'))
# Output:
h.images_with_size = False
h.images_as_html = True # always emit raw
print(h.handle('
'))
# Output:
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 He said See here. H2O and E=mc2 To be or not to be. italic and bold italic and bold Use the Hello, world! " + ("This is a very long paragraph with lots of text. " * 5) + " Project Overview Updated quarterly run_pipeline() Hello, world! dash—here © 2024 dash—here © 2024 First paragraph. Second paragraph. deleted kept Text before link text after. Price: $10 *approx* [see note] Use #hashtags and _underscores_ freely! 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("
hello
.` 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('
'))
```
### Response Example (Image Handling)
```
A photo
```
### Request Example (Table Handling)
```python
table_html = """
"""
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("Name Score Alice 95 Bob 87
"))
```
--------------------------------
### 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("
"))
```
--------------------------------
### 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("def hello():
print('hi')
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 = """
"""
# 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("
def greet(name):
return f"Hello, {name}!"
print(greet("world"))
<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("print() function.
&
```
--------------------------------
### 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("` 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
"))
```
--------------------------------
### 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("