html-to-markdown 1.8.0__py3-none-any.whl → 1.9.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,13 +3,13 @@ from __future__ import annotations
3
3
  from typing import TYPE_CHECKING
4
4
 
5
5
  if TYPE_CHECKING:
6
- from collections.abc import Generator, Mapping
6
+ from collections.abc import Callable, Generator, Mapping
7
7
 
8
8
  import re
9
9
  from contextvars import ContextVar
10
10
  from io import StringIO
11
11
  from itertools import chain
12
- from typing import TYPE_CHECKING, Any, Callable, Literal, cast
12
+ from typing import TYPE_CHECKING, Any, Literal, cast
13
13
 
14
14
  from bs4 import BeautifulSoup, Comment, Doctype, Tag
15
15
  from bs4.element import NavigableString, PageElement
@@ -176,7 +176,7 @@ def _process_tag(
176
176
  tag_name: SupportedTag | None = (
177
177
  cast("SupportedTag", tag.name.lower()) if tag.name.lower() in converters_map else None
178
178
  )
179
- text = ""
179
+ text_parts: list[str] = []
180
180
 
181
181
  is_heading = html_heading_re.match(tag.name) is not None
182
182
  is_cell = tag_name in {"td", "th"}
@@ -193,27 +193,51 @@ def _process_tag(
193
193
  if can_extract and isinstance(el, NavigableString) and not el.strip():
194
194
  el.extract()
195
195
 
196
- for el in filter(lambda value: not isinstance(value, (Comment, Doctype)), tag.children):
196
+ children = list(filter(lambda value: not isinstance(value, (Comment, Doctype)), tag.children))
197
+
198
+ empty_when_no_content_tags = {"abbr", "var", "ins", "dfn", "time", "data", "cite", "q", "mark", "small", "u"}
199
+
200
+ for i, el in enumerate(children):
197
201
  if isinstance(el, NavigableString):
198
- text += _process_text(
199
- el=el,
200
- escape_misc=escape_misc,
201
- escape_asterisks=escape_asterisks,
202
- escape_underscores=escape_underscores,
202
+ if el.strip() == "" and i > 0 and i < len(children) - 1:
203
+ prev_el = children[i - 1]
204
+ next_el = children[i + 1]
205
+
206
+ if (
207
+ isinstance(prev_el, Tag)
208
+ and isinstance(next_el, Tag)
209
+ and prev_el.name.lower() in empty_when_no_content_tags
210
+ and next_el.name.lower() in empty_when_no_content_tags
211
+ and not prev_el.get_text().strip()
212
+ ):
213
+ continue
214
+
215
+ text_parts.append(
216
+ _process_text(
217
+ el=el,
218
+ escape_misc=escape_misc,
219
+ escape_asterisks=escape_asterisks,
220
+ escape_underscores=escape_underscores,
221
+ )
203
222
  )
204
223
  elif isinstance(el, Tag):
205
- text += _process_tag(
206
- el,
207
- converters_map,
208
- convert_as_inline=convert_children_as_inline,
209
- convert=convert,
210
- escape_asterisks=escape_asterisks,
211
- escape_misc=escape_misc,
212
- escape_underscores=escape_underscores,
213
- strip=strip,
214
- context_before=(context_before + text)[-2:],
224
+ current_text = "".join(text_parts)
225
+ text_parts.append(
226
+ _process_tag(
227
+ el,
228
+ converters_map,
229
+ convert_as_inline=convert_children_as_inline,
230
+ convert=convert,
231
+ escape_asterisks=escape_asterisks,
232
+ escape_misc=escape_misc,
233
+ escape_underscores=escape_underscores,
234
+ strip=strip,
235
+ context_before=(context_before + current_text)[-2:],
236
+ )
215
237
  )
216
238
 
239
+ text = "".join(text_parts)
240
+
217
241
  if tag_name and should_convert_tag:
218
242
  rendered = converters_map[tag_name]( # type: ignore[call-arg]
219
243
  tag=tag, text=text, convert_as_inline=convert_as_inline
@@ -252,22 +276,68 @@ def _process_text(
252
276
  break
253
277
 
254
278
  if "pre" not in ancestor_names:
255
- has_leading_space = text.startswith((" ", "\t"))
256
-
257
- has_trailing_space = text.endswith((" ", "\t"))
258
-
259
- middle_content = (
260
- text[1:-1]
261
- if has_leading_space and has_trailing_space
262
- else text[1:]
263
- if has_leading_space
264
- else text[:-1]
265
- if has_trailing_space
266
- else text
267
- )
279
+ if text.strip() == "":
280
+ if "\n" in text:
281
+ text = ""
282
+ else:
283
+ block_elements = {
284
+ "p",
285
+ "ul",
286
+ "ol",
287
+ "div",
288
+ "blockquote",
289
+ "pre",
290
+ "h1",
291
+ "h2",
292
+ "h3",
293
+ "h4",
294
+ "h5",
295
+ "h6",
296
+ "table",
297
+ "dl",
298
+ "hr",
299
+ "figure",
300
+ "article",
301
+ "section",
302
+ "nav",
303
+ "aside",
304
+ "header",
305
+ "footer",
306
+ "main",
307
+ "form",
308
+ "fieldset",
309
+ }
310
+
311
+ prev_sibling = el.previous_sibling
312
+ next_sibling = el.next_sibling
313
+
314
+ if (
315
+ prev_sibling
316
+ and hasattr(prev_sibling, "name")
317
+ and prev_sibling.name in block_elements
318
+ and next_sibling
319
+ and hasattr(next_sibling, "name")
320
+ and next_sibling.name in block_elements
321
+ ):
322
+ text = ""
323
+ else:
324
+ text = " " if text else ""
325
+ else:
326
+ has_leading_space = text.startswith((" ", "\t"))
327
+ has_trailing_space = text.endswith((" ", "\t"))
328
+
329
+ middle_content = (
330
+ text[1:-1]
331
+ if has_leading_space and has_trailing_space
332
+ else text[1:]
333
+ if has_leading_space
334
+ else text[:-1]
335
+ if has_trailing_space
336
+ else text
337
+ )
268
338
 
269
- middle_content = whitespace_re.sub(" ", middle_content.strip())
270
- text = (" " if has_leading_space else "") + middle_content + (" " if has_trailing_space else "")
339
+ middle_content = whitespace_re.sub(" ", middle_content.strip())
340
+ text = (" " if has_leading_space else "") + middle_content + (" " if has_trailing_space else "")
271
341
 
272
342
  if not ancestor_names.intersection({"pre", "code", "kbd", "samp"}):
273
343
  text = escape(
@@ -388,7 +458,8 @@ def _extract_metadata(soup: BeautifulSoup) -> dict[str, str]:
388
458
  if canonical and isinstance(canonical, Tag) and isinstance(canonical["href"], str):
389
459
  metadata["canonical"] = canonical["href"]
390
460
 
391
- for rel_type in ["author", "license", "alternate"]:
461
+ link_relations = {"author", "license", "alternate"}
462
+ for rel_type in link_relations:
392
463
  link = soup.find("link", rel=rel_type, href=True)
393
464
  if link and isinstance(link, Tag) and isinstance(link["href"], str):
394
465
  metadata[f"link-{rel_type}"] = link["href"]
@@ -511,8 +582,6 @@ def convert_to_markdown(
511
582
  if strip_newlines:
512
583
  source = source.replace("\n", " ").replace("\r", " ")
513
584
 
514
- # Fix lxml parsing of void elements like <wbr>
515
- # lxml incorrectly treats them as container tags
516
585
  source = re.sub(r"<wbr\s*>", "<wbr />", source, flags=re.IGNORECASE)
517
586
 
518
587
  if preprocess_html and create_preprocessor is not None and preprocess_fn is not None:
@@ -653,7 +722,8 @@ def convert_to_markdown(
653
722
  if leading_whitespace_match:
654
723
  leading_whitespace = leading_whitespace_match.group(0)
655
724
 
656
- if any(tag in original_input for tag in ["<ol", "<ul", "<li", "<h1", "<h2", "<h3", "<h4", "<h5", "<h6"]):
725
+ list_heading_tags = {"<ol", "<ul", "<li", "<h1", "<h2", "<h3", "<h4", "<h5", "<h6"}
726
+ if any(tag in original_input for tag in list_heading_tags):
657
727
  leading_newlines = re.match(r"^[\n\r]*", leading_whitespace)
658
728
  leading_whitespace = leading_newlines.group(0) if leading_newlines else ""
659
729
 
@@ -665,13 +735,18 @@ def convert_to_markdown(
665
735
  def normalize_spaces_outside_code(text: str) -> str:
666
736
  parts = text.split("```")
667
737
  for i in range(0, len(parts), 2):
668
- # Preserve definition list formatting (: followed by 3 spaces)
669
- # Split by definition list patterns to preserve them
670
- def_parts = re.split(r"(:\s{3})", parts[i])
671
- for j in range(0, len(def_parts), 2):
672
- # Only normalize non-definition-list parts
673
- def_parts[j] = re.sub(r" {3,}", " ", def_parts[j])
674
- parts[i] = "".join(def_parts)
738
+ lines = parts[i].split("\n")
739
+ processed_lines = []
740
+ for line in lines:
741
+ def_parts = re.split(r"(:\s{3})", line)
742
+ for j in range(0, len(def_parts), 2):
743
+ match = re.match(r"^(\s*)(.*)", def_parts[j])
744
+ if match:
745
+ leading_spaces, rest = match.groups()
746
+ rest = re.sub(r" {3,}", " ", rest)
747
+ def_parts[j] = leading_spaces + rest
748
+ processed_lines.append("".join(def_parts))
749
+ parts[i] = "\n".join(processed_lines)
675
750
  return "```".join(parts)
676
751
 
677
752
  result = normalize_spaces_outside_code(result)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: html-to-markdown
3
- Version: 1.8.0
3
+ Version: 1.9.1
4
4
  Summary: A modern, type-safe Python library for converting HTML to Markdown with comprehensive tag support and customizable options
5
5
  Author-email: Na'aman Hirschfeld <nhirschfeld@gmail.com>
6
6
  License: MIT
@@ -15,7 +15,6 @@ Classifier: Intended Audience :: Developers
15
15
  Classifier: License :: OSI Approved :: MIT License
16
16
  Classifier: Operating System :: OS Independent
17
17
  Classifier: Programming Language :: Python :: 3 :: Only
18
- Classifier: Programming Language :: Python :: 3.9
19
18
  Classifier: Programming Language :: Python :: 3.10
20
19
  Classifier: Programming Language :: Python :: 3.11
21
20
  Classifier: Programming Language :: Python :: 3.12
@@ -28,13 +27,13 @@ Classifier: Topic :: Text Processing :: Markup :: HTML
28
27
  Classifier: Topic :: Text Processing :: Markup :: Markdown
29
28
  Classifier: Topic :: Utilities
30
29
  Classifier: Typing :: Typed
31
- Requires-Python: >=3.9
30
+ Requires-Python: >=3.10
32
31
  Description-Content-Type: text/markdown
33
32
  License-File: LICENSE
34
- Requires-Dist: beautifulsoup4>=4.13.4
35
- Requires-Dist: nh3>=0.2.21
33
+ Requires-Dist: beautifulsoup4>=4.13.5
34
+ Requires-Dist: nh3>=0.3
36
35
  Provides-Extra: lxml
37
- Requires-Dist: lxml>=5; extra == "lxml"
36
+ Requires-Dist: lxml>=6.0.1; extra == "lxml"
38
37
  Dynamic: license-file
39
38
 
40
39
  # html-to-markdown
@@ -43,9 +42,18 @@ A modern, fully typed Python library for converting HTML to Markdown. This libra
43
42
  of [markdownify](https://pypi.org/project/markdownify/) with a modernized codebase, strict type safety and support for
44
43
  Python 3.9+.
45
44
 
45
+ ## Support This Project
46
+
47
+ If you find html-to-markdown useful, please consider sponsoring the development:
48
+
49
+ <a href="https://github.com/sponsors/Goldziher"><img src="https://img.shields.io/badge/Sponsor-%E2%9D%A4-pink?logo=github-sponsors" alt="Sponsor on GitHub" height="32"></a>
50
+
51
+ Your support helps maintain and improve this library for the community! 🚀
52
+
46
53
  ## Features
47
54
 
48
55
  - **Full HTML5 Support**: Comprehensive support for all modern HTML5 elements including semantic, form, table, ruby, interactive, structural, SVG, and math elements
56
+ - **Enhanced Table Support**: Advanced handling of merged cells with rowspan/colspan support for better table representation
49
57
  - **Type Safety**: Strict MyPy adherence with comprehensive type hints
50
58
  - **Metadata Extraction**: Automatic extraction of document metadata (title, meta tags) as comment headers
51
59
  - **Streaming Support**: Memory-efficient processing for large documents with progress callbacks
@@ -55,7 +63,7 @@ Python 3.9+.
55
63
  - **CLI Tool**: Full-featured command-line interface with all API options exposed
56
64
  - **Custom Converters**: Extensible converter system for custom HTML tag handling
57
65
  - **BeautifulSoup Integration**: Support for pre-configured BeautifulSoup instances
58
- - **Extensive Test Coverage**: 100% test coverage requirement with comprehensive test suite
66
+ - **Comprehensive Test Coverage**: 91%+ test coverage with 623+ comprehensive tests
59
67
 
60
68
  ## Installation
61
69
 
@@ -203,6 +211,51 @@ print(markdown)
203
211
 
204
212
  Custom converters take precedence over the built-in converters and can be used alongside other configuration options.
205
213
 
214
+ ### Enhanced Table Support
215
+
216
+ The library now provides better handling of complex tables with merged cells:
217
+
218
+ ```python
219
+ from html_to_markdown import convert_to_markdown
220
+
221
+ # HTML table with merged cells
222
+ html = """
223
+ <table>
224
+ <tr>
225
+ <th rowspan="2">Category</th>
226
+ <th colspan="2">Sales Data</th>
227
+ </tr>
228
+ <tr>
229
+ <th>Q1</th>
230
+ <th>Q2</th>
231
+ </tr>
232
+ <tr>
233
+ <td>Product A</td>
234
+ <td>$100K</td>
235
+ <td>$150K</td>
236
+ </tr>
237
+ </table>
238
+ """
239
+
240
+ markdown = convert_to_markdown(html)
241
+ print(markdown)
242
+ ```
243
+
244
+ Output:
245
+
246
+ ```markdown
247
+ | Category | Sales Data | |
248
+ | --- | --- | --- |
249
+ | | Q1 | Q2 |
250
+ | Product A | $100K | $150K |
251
+ ```
252
+
253
+ The library handles:
254
+
255
+ - **Rowspan**: Inserts empty cells in subsequent rows
256
+ - **Colspan**: Properly manages column spanning
257
+ - **Clean output**: Removes `<colgroup>` and `<col>` elements that have no Markdown equivalent
258
+
206
259
  ### Key Configuration Options
207
260
 
208
261
  | Option | Type | Default | Description |
@@ -438,7 +491,9 @@ This library provides comprehensive support for all modern HTML5 elements:
438
491
 
439
492
  ### Table Elements
440
493
 
441
- - `<table>`, `<thead>`, `<tbody>`, `<tfoot>`, `<tr>`, `<th>`, `<td>`, `<caption>`, `<col>`, `<colgroup>`
494
+ - `<table>`, `<thead>`, `<tbody>`, `<tfoot>`, `<tr>`, `<th>`, `<td>`, `<caption>`
495
+ - **Merged cell support**: Handles `rowspan` and `colspan` attributes for complex table layouts
496
+ - **Smart cleanup**: Automatically handles table styling elements for clean Markdown output
442
497
 
443
498
  ### Interactive Elements
444
499
 
@@ -457,16 +512,41 @@ This library provides comprehensive support for all modern HTML5 elements:
457
512
 
458
513
  - `<math>` (MathML support)
459
514
 
460
- ## Breaking Changes (Major Version)
515
+ ## Advanced Table Support
516
+
517
+ The library provides sophisticated handling of complex HTML tables, including merged cells and proper structure conversion:
518
+
519
+ ```python
520
+ from html_to_markdown import convert_to_markdown
521
+
522
+ # Complex table with merged cells
523
+ html = """
524
+ <table>
525
+ <caption>Sales Report</caption>
526
+ <tr>
527
+ <th rowspan="2">Product</th>
528
+ <th colspan="2">Quarterly Sales</th>
529
+ </tr>
530
+ <tr>
531
+ <th>Q1</th>
532
+ <th>Q2</th>
533
+ </tr>
534
+ <tr>
535
+ <td>Widget A</td>
536
+ <td>$50K</td>
537
+ <td>$75K</td>
538
+ </tr>
539
+ </table>
540
+ """
541
+
542
+ result = convert_to_markdown(html)
543
+ ```
461
544
 
462
- This version introduces several breaking changes for improved consistency and functionality:
545
+ **Features:**
463
546
 
464
- 1. **Enhanced Metadata Extraction**: Now enabled by default with comprehensive extraction of title, meta tags, and link relations
465
- 1. **Improved Newline Handling**: Better normalization of excessive newlines (max 2 consecutive)
466
- 1. **Extended HTML5 Support**: Added support for 40+ new HTML5 elements
467
- 1. **Streaming API**: New streaming parameters for large document processing
468
- 1. **Task List Support**: Automatic conversion of HTML checkboxes to GitHub-compatible task lists
469
- 1. **Highlight Styles**: New `highlight_style` parameter with multiple options for `<mark>` elements
547
+ - **Merged cell support**: Handles `rowspan` and `colspan` attributes intelligently
548
+ - **Clean output**: Automatically removes table styling elements that don't translate to Markdown
549
+ - **Structure preservation**: Maintains table hierarchy and relationships
470
550
 
471
551
  ## Acknowledgments
472
552
 
@@ -2,15 +2,15 @@ html_to_markdown/__init__.py,sha256=TzZzhZDJHeXW_3B9zceYehz2zlttqdLsDr5un8stZLM,
2
2
  html_to_markdown/__main__.py,sha256=DJyJX7NIK0BVPNS2r3BYJ0Ci_lKHhgVOpw7ZEqACH3c,323
3
3
  html_to_markdown/cli.py,sha256=8xlgSEcnqsSM_dr1TCSgPDAo09YvUtO78PvDFivFFdg,6973
4
4
  html_to_markdown/constants.py,sha256=8vqANd-7wYvDzBm1VXZvdIxS4Xom4Ov_Yghg6jvmyio,584
5
- html_to_markdown/converters.py,sha256=COC2KqPelJlMCY5eXUS5gdiPOG8Yzx0U719FeXPw3GA,55514
5
+ html_to_markdown/converters.py,sha256=n0OeRnfDc7sH2j5oOuqJQmxySJxRFdfpPRHcrHJXFGE,46869
6
6
  html_to_markdown/exceptions.py,sha256=s1DaG6A23rOurF91e4jryuUzplWcC_JIAuK9_bw_4jQ,1558
7
7
  html_to_markdown/preprocessor.py,sha256=S4S1ZfLC_hkJVgmA5atImTyWQDOxfHctPbaep2QtyrQ,11248
8
- html_to_markdown/processing.py,sha256=wkbhLg42U3aeVQSZFuzGt5irtN037XzRKpCE71QYZXI,36520
8
+ html_to_markdown/processing.py,sha256=ephjzcUJOilId8Z6AScaMY6AKkyNq9N0A1DMt9HfVuk,39068
9
9
  html_to_markdown/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
10
  html_to_markdown/utils.py,sha256=QgWPzmpZKFd6wDTe8IY3gbVT3xNzoGV3PBgd17J0O-w,2066
11
- html_to_markdown-1.8.0.dist-info/licenses/LICENSE,sha256=3J_HR5BWvUM1mlIrlkF32-uC1FM64gy8JfG17LBuheQ,1122
12
- html_to_markdown-1.8.0.dist-info/METADATA,sha256=6pgiK4p0A77axLfD8MH1EGgzifP06koVV8KWS_5-iYk,17175
13
- html_to_markdown-1.8.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
14
- html_to_markdown-1.8.0.dist-info/entry_points.txt,sha256=xmFijrTfgYW7lOrZxZGRPciicQHa5KiXKkUhBCmICtQ,116
15
- html_to_markdown-1.8.0.dist-info/top_level.txt,sha256=Ev6djb1c4dSKr_-n4K-FpEGDkzBigXY6LuZ5onqS7AE,17
16
- html_to_markdown-1.8.0.dist-info/RECORD,,
11
+ html_to_markdown-1.9.1.dist-info/licenses/LICENSE,sha256=3J_HR5BWvUM1mlIrlkF32-uC1FM64gy8JfG17LBuheQ,1122
12
+ html_to_markdown-1.9.1.dist-info/METADATA,sha256=FUHr7dId_1ZQfgKjPcInKwvwBChyxlyPMIwYl0Z4dko,18813
13
+ html_to_markdown-1.9.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
14
+ html_to_markdown-1.9.1.dist-info/entry_points.txt,sha256=xmFijrTfgYW7lOrZxZGRPciicQHa5KiXKkUhBCmICtQ,116
15
+ html_to_markdown-1.9.1.dist-info/top_level.txt,sha256=Ev6djb1c4dSKr_-n4K-FpEGDkzBigXY6LuZ5onqS7AE,17
16
+ html_to_markdown-1.9.1.dist-info/RECORD,,