Compare commits
226 Commits
0.2.0
...
pyproject.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c23c0655f | ||
|
|
e2ace9d633 | ||
|
|
a5615f7d80 | ||
|
|
f6c8daf8a5 | ||
|
|
75a678dab9 | ||
|
|
0a5c89aa49 | ||
|
|
51390d7389 | ||
|
|
50b4640db2 | ||
|
|
7861b330cd | ||
|
|
2ec33384de | ||
|
|
c1672aee44 | ||
|
|
43dbe20aaf | ||
|
|
46af45bb3c | ||
|
|
2bd0772685 | ||
|
|
74ddc408cc | ||
|
|
3b4a014f25 | ||
|
|
57d4f37923 | ||
|
|
d5fb0fbb85 | ||
|
|
e4df41225d | ||
|
|
804a3f8f07 | ||
|
|
7d0bf46057 | ||
|
|
2f9a42d3b8 | ||
|
|
96a25cfbf3 | ||
|
|
0477a0c8a0 | ||
|
|
f33ccd7c1a | ||
|
|
a2f82678f7 | ||
|
|
60967c1c95 | ||
|
|
c7718b6d81 | ||
|
|
2b22d239ad | ||
|
|
67100595ae | ||
|
|
deba8b5e54 | ||
|
|
ca88e4e49d | ||
|
|
e6e23fd512 | ||
|
|
433fad2dec | ||
|
|
4fb451ffa6 | ||
|
|
e8d041c251 | ||
|
|
f729c3ba43 | ||
|
|
eddfdae4ca | ||
|
|
50b3b73a8f | ||
|
|
0310216877 | ||
|
|
9914474828 | ||
|
|
6263f0e5f0 | ||
|
|
17d8586843 | ||
|
|
59eb069700 | ||
|
|
e79971a7eb | ||
|
|
5adda130b8 | ||
|
|
5f1b98e25d | ||
|
|
16acd2b763 | ||
|
|
207d0f4ec6 | ||
|
|
ebb9ea713d | ||
|
|
87b9f6c88e | ||
|
|
bda367dad9 | ||
|
|
61e8940486 | ||
|
|
35479d2d3b | ||
|
|
b589863715 | ||
|
|
423b7e948c | ||
|
|
0ea95de4d0 | ||
|
|
ed3eee78d2 | ||
|
|
ddda696396 | ||
|
|
0a1343a538 | ||
|
|
9d0b839b73 | ||
|
|
d3eff11617 | ||
|
|
bd6b581122 | ||
|
|
c8f7cf63e3 | ||
|
|
12a68a7d14 | ||
|
|
478b1c7e13 | ||
|
|
ffcf6cbcb2 | ||
|
|
0ab0452414 | ||
|
|
b62b067cbd | ||
|
|
cb2646cd93 | ||
|
|
9692b5e714 | ||
|
|
ac68c53a7d | ||
|
|
40dd30419c | ||
|
|
da56f7f56a | ||
|
|
8400b39dd9 | ||
|
|
5fc1441fe7 | ||
|
|
044615eff1 | ||
|
|
dbd9f3f3d2 | ||
|
|
0fdeb1ff6e | ||
|
|
6a2f3a4b42 | ||
|
|
22180a166d | ||
|
|
16d8a0e1f7 | ||
|
|
4aa6cf2a24 | ||
|
|
828e116530 | ||
|
|
62e9f0de02 | ||
|
|
cec570fc49 | ||
|
|
a6a31624ad | ||
|
|
6f3732307d | ||
|
|
8f6d7e500d | ||
|
|
e96351b666 | ||
|
|
129c4ef060 | ||
|
|
9cb940cbc0 | ||
|
|
70ef9b6e48 | ||
|
|
91d53ddd5a | ||
|
|
079f32f6cd | ||
|
|
89b577e91e | ||
|
|
4bf2ea44fc | ||
|
|
77797ebb79 | ||
|
|
9f3c4c9fa0 | ||
|
|
967db26b3a | ||
|
|
ea81407b87 | ||
|
|
e6da15c173 | ||
|
|
7dac92e85e | ||
|
|
fc29483899 | ||
|
|
bd7a8d6990 | ||
|
|
ddfbf6a364 | ||
|
|
91a64e3cd4 | ||
|
|
0fee4b0a80 | ||
|
|
10e1ff3e6e | ||
|
|
73800ced36 | ||
|
|
1538cacb94 | ||
|
|
f59f9f9a54 | ||
|
|
bd22a16c9e | ||
|
|
55fb96e3c0 | ||
|
|
5f102d5223 | ||
|
|
651d5f00e8 | ||
|
|
3cf324d03d | ||
|
|
96f7e7d307 | ||
|
|
e1dbbfad42 | ||
|
|
d4882b86b9 | ||
|
|
b47d5f11c8 | ||
|
|
29c794e17d | ||
|
|
e877602a5e | ||
|
|
5580b0b51d | ||
|
|
650f377b64 | ||
|
|
7ee87b1d32 | ||
|
|
16dbc471b9 | ||
|
|
c04ec855dd | ||
|
|
8da0bdf998 | ||
|
|
a59e4b9f48 | ||
|
|
fd293a9714 | ||
|
|
99365de669 | ||
|
|
ed406d3206 | ||
|
|
f320cf87ff | ||
|
|
a79ed44ec3 | ||
|
|
29a4e551f7 | ||
|
|
b3ac4606a6 | ||
|
|
f093843f40 | ||
|
|
de6f91af0e | ||
|
|
8c28ade348 | ||
|
|
a152c5b706 | ||
|
|
292d64bbf4 | ||
|
|
db96eeb785 | ||
|
|
73f7644c0d | ||
|
|
a4d134df97 | ||
|
|
457454c713 | ||
|
|
321e9eb5f6 | ||
|
|
77d1e99bd5 | ||
|
|
97c78ef55b | ||
|
|
b7e1ab889d | ||
|
|
29e86aec55 | ||
|
|
453b604096 | ||
|
|
4f8937810b | ||
|
|
3544322ed2 | ||
|
|
c4d0a14ce5 | ||
|
|
05ea8dc58a | ||
|
|
7780f82c30 | ||
|
|
7685738344 | ||
|
|
92a73c8dfe | ||
|
|
3354f143d8 | ||
|
|
d558617cd7 | ||
|
|
25d68b4265 | ||
|
|
5561106991 | ||
|
|
1b3136ad04 | ||
|
|
2c7e4a0100 | ||
|
|
4f00d638d2 | ||
|
|
987a2a9cae | ||
|
|
a4461161bc | ||
|
|
19e2c3db0d | ||
|
|
ba51bbee12 | ||
|
|
9f3d497053 | ||
|
|
d2fc689b66 | ||
|
|
ab78385b56 | ||
|
|
9ebf726e78 | ||
|
|
3f8403aa7a | ||
|
|
5b6e76f984 | ||
|
|
04711027e6 | ||
|
|
ca98892953 | ||
|
|
0dc281e6ea | ||
|
|
4e6e20e756 | ||
|
|
9358522c73 | ||
|
|
28d7a22da3 | ||
|
|
8b882ca3c9 | ||
|
|
1078610066 | ||
|
|
d23dbc77e4 | ||
|
|
0c4b856b9c | ||
|
|
e9cc01938a | ||
|
|
aceced68eb | ||
|
|
3b049cdb9c | ||
|
|
b747378b52 | ||
|
|
ee73d89879 | ||
|
|
d23596706d | ||
|
|
6a0e5d8176 | ||
|
|
7b788bafd4 | ||
|
|
146104b41f | ||
|
|
5563161c86 | ||
|
|
28e447d9ae | ||
|
|
89d14f4487 | ||
|
|
5f9243d91d | ||
|
|
d0f688d2e4 | ||
|
|
5ac08522be | ||
|
|
78afcc173e | ||
|
|
b132a6f5b3 | ||
|
|
0abe0a29e8 | ||
|
|
4932df631f | ||
|
|
8696e2bde1 | ||
|
|
ee53d85c41 | ||
|
|
53ba0daa77 | ||
|
|
fb98e9878f | ||
|
|
aa10053fbb | ||
|
|
253a34c2d7 | ||
|
|
3ea09609e6 | ||
|
|
1cd8e56c47 | ||
|
|
891a4a8d08 | ||
|
|
e5a1784f30 | ||
|
|
f60d910335 | ||
|
|
d707d107f6 | ||
|
|
1ef4dd1468 | ||
|
|
934c97b342 | ||
|
|
8a1e2d9403 | ||
|
|
5563723cbc | ||
|
|
a9c13a56da | ||
|
|
7bdeb15b18 | ||
|
|
87c8f3bd5e | ||
|
|
0211ac6619 | ||
|
|
2515e9e107 |
32
.github/workflows/python-app.yml
vendored
Normal file
32
.github/workflows/python-app.yml
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
# This workflow will install Python dependencies, run tests and lint with a single version of Python
|
||||
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
|
||||
|
||||
name: Python application
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ develop ]
|
||||
pull_request:
|
||||
branches: [ develop ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Set up Python 3.8
|
||||
uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: 3.8
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install --upgrade setuptools setuptools_scm wheel build tox
|
||||
- name: Lint and test
|
||||
run: |
|
||||
tox
|
||||
- name: Build
|
||||
run: |
|
||||
python -m build -nwsx .
|
||||
31
.github/workflows/python-publish.yml
vendored
Normal file
31
.github/workflows/python-publish.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
# This workflow will upload a Python Package using Twine when a release is created
|
||||
# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries
|
||||
|
||||
name: Upload Python Package
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [created]
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v2
|
||||
with:
|
||||
python-version: '3.8'
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install --upgrade setuptools setuptools_scm wheel build twine
|
||||
- name: Build and publish
|
||||
env:
|
||||
TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
|
||||
TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
|
||||
run: |
|
||||
python -m build -nwsx .
|
||||
twine upload dist/*
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -1,7 +1,12 @@
|
||||
*.pyc
|
||||
*.egg
|
||||
.eggs/
|
||||
*.egg-info/
|
||||
.DS_Store
|
||||
/.env
|
||||
/dist
|
||||
/MANIFEST
|
||||
/venv
|
||||
build/
|
||||
.vscode/settings.json
|
||||
.tox/
|
||||
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright 2012-2018 Matthew Tretter
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1 +1,2 @@
|
||||
include README.rst
|
||||
prune tests
|
||||
|
||||
193
README.rst
193
README.rst
@@ -1,3 +1,21 @@
|
||||
|build| |version| |license| |downloads|
|
||||
|
||||
.. |build| image:: https://img.shields.io/github/actions/workflow/status/matthewwithanm/python-markdownify/python-app.yml?branch=develop
|
||||
:alt: GitHub Workflow Status
|
||||
:target: https://github.com/matthewwithanm/python-markdownify/actions/workflows/python-app.yml?query=workflow%3A%22Python+application%22
|
||||
|
||||
.. |version| image:: https://img.shields.io/pypi/v/markdownify
|
||||
:alt: Pypi version
|
||||
:target: https://pypi.org/project/markdownify/
|
||||
|
||||
.. |license| image:: https://img.shields.io/pypi/l/markdownify
|
||||
:alt: License
|
||||
:target: https://github.com/matthewwithanm/python-markdownify/blob/develop/LICENSE
|
||||
|
||||
.. |downloads| image:: https://pepy.tech/badge/markdownify
|
||||
:alt: Pypi Downloads
|
||||
:target: https://pepy.tech/project/markdownify
|
||||
|
||||
Installation
|
||||
============
|
||||
|
||||
@@ -14,16 +32,187 @@ Convert some HTML to Markdown:
|
||||
from markdownify import markdownify as md
|
||||
md('<b>Yay</b> <a href="http://github.com">GitHub</a>') # > '**Yay** [GitHub](http://github.com)'
|
||||
|
||||
Specify tags to exclude (blacklist):
|
||||
Specify tags to exclude:
|
||||
|
||||
.. code:: python
|
||||
|
||||
from markdownify import markdownify as md
|
||||
md('<b>Yay</b> <a href="http://github.com">GitHub</a>', strip=['a']) # > '**Yay** GitHub'
|
||||
|
||||
\...or specify the tags you want to include (whitelist):
|
||||
\...or specify the tags you want to include:
|
||||
|
||||
.. code:: python
|
||||
|
||||
from markdownify import markdownify as md
|
||||
md('<b>Yay</b> <a href="http://github.com">GitHub</a>', convert=['b']) # > '**Yay** GitHub'
|
||||
|
||||
|
||||
Options
|
||||
=======
|
||||
|
||||
Markdownify supports the following options:
|
||||
|
||||
strip
|
||||
A list of tags to strip. This option can't be used with the
|
||||
``convert`` option.
|
||||
|
||||
convert
|
||||
A list of tags to convert. This option can't be used with the
|
||||
``strip`` option.
|
||||
|
||||
autolinks
|
||||
A boolean indicating whether the "automatic link" style should be used when
|
||||
a ``a`` tag's contents match its href. Defaults to ``True``.
|
||||
|
||||
default_title
|
||||
A boolean to enable setting the title of a link to its href, if no title is
|
||||
given. Defaults to ``False``.
|
||||
|
||||
heading_style
|
||||
Defines how headings should be converted. Accepted values are ``ATX``,
|
||||
``ATX_CLOSED``, ``SETEXT``, and ``UNDERLINED`` (which is an alias for
|
||||
``SETEXT``). Defaults to ``UNDERLINED``.
|
||||
|
||||
bullets
|
||||
An iterable (string, list, or tuple) of bullet styles to be used. If the
|
||||
iterable only contains one item, it will be used regardless of how deeply
|
||||
lists are nested. Otherwise, the bullet will alternate based on nesting
|
||||
level. Defaults to ``'*+-'``.
|
||||
|
||||
strong_em_symbol
|
||||
In markdown, both ``*`` and ``_`` are used to encode **strong** or
|
||||
*emphasized* texts. Either of these symbols can be chosen by the options
|
||||
``ASTERISK`` (default) or ``UNDERSCORE`` respectively.
|
||||
|
||||
sub_symbol, sup_symbol
|
||||
Define the chars that surround ``<sub>`` and ``<sup>`` text. Defaults to an
|
||||
empty string, because this is non-standard behavior. Could be something like
|
||||
``~`` and ``^`` to result in ``~sub~`` and ``^sup^``. If the value starts
|
||||
with ``<`` and ends with ``>``, it is treated as an HTML tag and a ``/`` is
|
||||
inserted after the ``<`` in the string used after the text; this allows
|
||||
specifying ``<sub>`` to use raw HTML in the output for subscripts, for
|
||||
example.
|
||||
|
||||
newline_style
|
||||
Defines the style of marking linebreaks (``<br>``) in markdown. The default
|
||||
value ``SPACES`` of this option will adopt the usual two spaces and a newline,
|
||||
while ``BACKSLASH`` will convert a linebreak to ``\\n`` (a backslash and a
|
||||
newline). While the latter convention is non-standard, it is commonly
|
||||
preferred and supported by a lot of interpreters.
|
||||
|
||||
code_language
|
||||
Defines the language that should be assumed for all ``<pre>`` sections.
|
||||
Useful, if all code on a page is in the same programming language and
|
||||
should be annotated with `````python`` or similar.
|
||||
Defaults to ``''`` (empty string) and can be any string.
|
||||
|
||||
code_language_callback
|
||||
When the HTML code contains ``pre`` tags that in some way provide the code
|
||||
language, for example as class, this callback can be used to extract the
|
||||
language from the tag and prefix it to the converted ``pre`` tag.
|
||||
The callback gets one single argument, an BeautifylSoup object, and returns
|
||||
a string containing the code language, or ``None``.
|
||||
An example to use the class name as code language could be::
|
||||
|
||||
def callback(el):
|
||||
return el['class'][0] if el.has_attr('class') else None
|
||||
|
||||
Defaults to ``None``.
|
||||
|
||||
escape_asterisks
|
||||
If set to ``False``, do not escape ``*`` to ``\*`` in text.
|
||||
Defaults to ``True``.
|
||||
|
||||
escape_underscores
|
||||
If set to ``False``, do not escape ``_`` to ``\_`` in text.
|
||||
Defaults to ``True``.
|
||||
|
||||
escape_misc
|
||||
If set to ``False``, do not escape miscellaneous punctuation characters
|
||||
that sometimes have Markdown significance in text.
|
||||
Defaults to ``True``.
|
||||
|
||||
keep_inline_images_in
|
||||
Images are converted to their alt-text when the images are located inside
|
||||
headlines or table cells. If some inline images should be converted to
|
||||
markdown images instead, this option can be set to a list of parent tags
|
||||
that should be allowed to contain inline images, for example ``['td']``.
|
||||
Defaults to an empty list.
|
||||
|
||||
wrap, wrap_width
|
||||
If ``wrap`` is set to ``True``, all text paragraphs are wrapped at
|
||||
``wrap_width`` characters. Defaults to ``False`` and ``80``.
|
||||
Use with ``newline_style=BACKSLASH`` to keep line breaks in paragraphs.
|
||||
|
||||
Options may be specified as kwargs to the ``markdownify`` function, or as a
|
||||
nested ``Options`` class in ``MarkdownConverter`` subclasses.
|
||||
|
||||
|
||||
Converting BeautifulSoup objects
|
||||
================================
|
||||
|
||||
.. code:: python
|
||||
|
||||
from markdownify import MarkdownConverter
|
||||
|
||||
# Create shorthand method for conversion
|
||||
def md(soup, **options):
|
||||
return MarkdownConverter(**options).convert_soup(soup)
|
||||
|
||||
|
||||
Creating Custom Converters
|
||||
==========================
|
||||
|
||||
If you have a special usecase that calls for a special conversion, you can
|
||||
always inherit from ``MarkdownConverter`` and override the method you want to
|
||||
change.
|
||||
The function that handles a HTML tag named ``abc`` is called
|
||||
``convert_abc(self, el, text, convert_as_inline)`` and returns a string
|
||||
containing the converted HTML tag.
|
||||
The ``MarkdownConverter`` object will handle the conversion based on the
|
||||
function names:
|
||||
|
||||
.. code:: python
|
||||
|
||||
from markdownify import MarkdownConverter
|
||||
|
||||
class ImageBlockConverter(MarkdownConverter):
|
||||
"""
|
||||
Create a custom MarkdownConverter that adds two newlines after an image
|
||||
"""
|
||||
def convert_img(self, el, text, convert_as_inline):
|
||||
return super().convert_img(el, text, convert_as_inline) + '\n\n'
|
||||
|
||||
# Create shorthand method for conversion
|
||||
def md(html, **options):
|
||||
return ImageBlockConverter(**options).convert(html)
|
||||
|
||||
.. code:: python
|
||||
|
||||
from markdownify import MarkdownConverter
|
||||
|
||||
class IgnoreParagraphsConverter(MarkdownConverter):
|
||||
"""
|
||||
Create a custom MarkdownConverter that ignores paragraphs
|
||||
"""
|
||||
def convert_p(self, el, text, convert_as_inline):
|
||||
return ''
|
||||
|
||||
# Create shorthand method for conversion
|
||||
def md(html, **options):
|
||||
return IgnoreParagraphsConverter(**options).convert(html)
|
||||
|
||||
|
||||
Command Line Interface
|
||||
======================
|
||||
|
||||
Use ``markdownify example.html > example.md`` or pipe input from stdin
|
||||
(``cat example.html | markdownify > example.md``).
|
||||
Call ``markdownify -h`` to see all available options.
|
||||
They are the same as listed above and take the same arguments.
|
||||
|
||||
|
||||
Development
|
||||
===========
|
||||
|
||||
To run tests and the linter run ``pip install tox`` once, then ``tox``.
|
||||
|
||||
@@ -1,56 +1,191 @@
|
||||
from lxml.html.soupparser import fromstring
|
||||
from bs4 import BeautifulSoup, NavigableString, Comment, Doctype
|
||||
from textwrap import fill
|
||||
import re
|
||||
import six
|
||||
|
||||
|
||||
convert_heading_re = re.compile(r'convert_h(\d+)')
|
||||
line_beginning_re = re.compile(r'^', re.MULTILINE)
|
||||
whitespace_re = re.compile(r'[\r\n\s\t ]+')
|
||||
whitespace_re = re.compile(r'[\t ]+')
|
||||
all_whitespace_re = re.compile(r'[\s]+')
|
||||
html_heading_re = re.compile(r'h[1-6]')
|
||||
|
||||
|
||||
def escape(text):
|
||||
if not text:
|
||||
return ''
|
||||
return text.replace('_', r'\_')
|
||||
# Heading styles
|
||||
ATX = 'atx'
|
||||
ATX_CLOSED = 'atx_closed'
|
||||
UNDERLINED = 'underlined'
|
||||
SETEXT = UNDERLINED
|
||||
|
||||
# Newline style
|
||||
SPACES = 'spaces'
|
||||
BACKSLASH = 'backslash'
|
||||
|
||||
# Strong and emphasis style
|
||||
ASTERISK = '*'
|
||||
UNDERSCORE = '_'
|
||||
|
||||
|
||||
def chomp(text):
|
||||
"""
|
||||
If the text in an inline tag like b, a, or em contains a leading or trailing
|
||||
space, strip the string and return a space as suffix of prefix, if needed.
|
||||
This function is used to prevent conversions like
|
||||
<b> foo</b> => ** foo**
|
||||
"""
|
||||
prefix = ' ' if text and text[0] == ' ' else ''
|
||||
suffix = ' ' if text and text[-1] == ' ' else ''
|
||||
text = text.strip()
|
||||
return (prefix, suffix, text)
|
||||
|
||||
|
||||
def abstract_inline_conversion(markup_fn):
|
||||
"""
|
||||
This abstracts all simple inline tags like b, em, del, ...
|
||||
Returns a function that wraps the chomped text in a pair of the string
|
||||
that is returned by markup_fn, with '/' inserted in the string used after
|
||||
the text if it looks like an HTML tag. markup_fn is necessary to allow for
|
||||
references to self.strong_em_symbol etc.
|
||||
"""
|
||||
def implementation(self, el, text, convert_as_inline):
|
||||
markup_prefix = markup_fn(self)
|
||||
if markup_prefix.startswith('<') and markup_prefix.endswith('>'):
|
||||
markup_suffix = '</' + markup_prefix[1:]
|
||||
else:
|
||||
markup_suffix = markup_prefix
|
||||
if el.find_parent(['pre', 'code', 'kbd', 'samp']):
|
||||
return text
|
||||
prefix, suffix, text = chomp(text)
|
||||
if not text:
|
||||
return ''
|
||||
return '%s%s%s%s%s' % (prefix, markup_prefix, text, markup_suffix, suffix)
|
||||
return implementation
|
||||
|
||||
|
||||
def _todict(obj):
|
||||
return dict((k, getattr(obj, k)) for k in dir(obj) if not k.startswith('_'))
|
||||
|
||||
|
||||
class MarkdownConverter(object):
|
||||
def __init__(self, tags_to_strip=None, tags_to_convert=None):
|
||||
if tags_to_strip is not None and tags_to_convert is not None:
|
||||
class DefaultOptions:
|
||||
autolinks = True
|
||||
bullets = '*+-' # An iterable of bullet types.
|
||||
code_language = ''
|
||||
code_language_callback = None
|
||||
convert = None
|
||||
default_title = False
|
||||
escape_asterisks = True
|
||||
escape_underscores = True
|
||||
escape_misc = True
|
||||
heading_style = UNDERLINED
|
||||
keep_inline_images_in = []
|
||||
newline_style = SPACES
|
||||
strip = None
|
||||
strong_em_symbol = ASTERISK
|
||||
sub_symbol = ''
|
||||
sup_symbol = ''
|
||||
wrap = False
|
||||
wrap_width = 80
|
||||
|
||||
class Options(DefaultOptions):
|
||||
pass
|
||||
|
||||
def __init__(self, **options):
|
||||
# Create an options dictionary. Use DefaultOptions as a base so that
|
||||
# it doesn't have to be extended.
|
||||
self.options = _todict(self.DefaultOptions)
|
||||
self.options.update(_todict(self.Options))
|
||||
self.options.update(options)
|
||||
if self.options['strip'] is not None and self.options['convert'] is not None:
|
||||
raise ValueError('You may specify either tags to strip or tags to'
|
||||
' convert, but not both.')
|
||||
self.tags_to_strip = tags_to_strip
|
||||
self.tags_to_convert = tags_to_convert
|
||||
' convert, but not both.')
|
||||
|
||||
def convert(self, html):
|
||||
soup = fromstring(html)
|
||||
return self.process_tag(soup)
|
||||
soup = BeautifulSoup(html, 'html.parser')
|
||||
return self.convert_soup(soup)
|
||||
|
||||
def process_tag(self, node):
|
||||
text = self.process_text(node.text)
|
||||
def convert_soup(self, soup):
|
||||
return self.process_tag(soup, convert_as_inline=False, children_only=True)
|
||||
|
||||
def process_tag(self, node, convert_as_inline, children_only=False):
|
||||
text = ''
|
||||
|
||||
# markdown headings or cells can't include
|
||||
# block elements (elements w/newlines)
|
||||
isHeading = html_heading_re.match(node.name) is not None
|
||||
isCell = node.name in ['td', 'th']
|
||||
convert_children_as_inline = convert_as_inline
|
||||
|
||||
if not children_only and (isHeading or isCell):
|
||||
convert_children_as_inline = True
|
||||
|
||||
# Remove whitespace-only textnodes in purely nested nodes
|
||||
def is_nested_node(el):
|
||||
return el and el.name in ['ol', 'ul', 'li',
|
||||
'table', 'thead', 'tbody', 'tfoot',
|
||||
'tr', 'td', 'th']
|
||||
|
||||
if is_nested_node(node):
|
||||
for el in node.children:
|
||||
# Only extract (remove) whitespace-only text node if any of the
|
||||
# conditions is true:
|
||||
# - el is the first element in its parent
|
||||
# - el is the last element in its parent
|
||||
# - el is adjacent to an nested node
|
||||
can_extract = (not el.previous_sibling
|
||||
or not el.next_sibling
|
||||
or is_nested_node(el.previous_sibling)
|
||||
or is_nested_node(el.next_sibling))
|
||||
if (isinstance(el, NavigableString)
|
||||
and six.text_type(el).strip() == ''
|
||||
and can_extract):
|
||||
el.extract()
|
||||
|
||||
# Convert the children first
|
||||
for el in node.findall('*'):
|
||||
text += self.process_tag(el)
|
||||
for el in node.children:
|
||||
if isinstance(el, Comment) or isinstance(el, Doctype):
|
||||
continue
|
||||
elif isinstance(el, NavigableString):
|
||||
text += self.process_text(el)
|
||||
else:
|
||||
text += self.process_tag(el, convert_children_as_inline)
|
||||
|
||||
convert_fn = getattr(self, 'convert_%s' % node.tag, None)
|
||||
if convert_fn and self.should_convert_tag(node.tag):
|
||||
text = convert_fn(node, text)
|
||||
|
||||
text += self.process_text(node.tail)
|
||||
if not children_only:
|
||||
convert_fn = getattr(self, 'convert_%s' % node.name, None)
|
||||
if convert_fn and self.should_convert_tag(node.name):
|
||||
text = convert_fn(node, text, convert_as_inline)
|
||||
|
||||
return text
|
||||
|
||||
def process_text(self, text):
|
||||
return escape(whitespace_re.sub(' ', text or ''))
|
||||
def process_text(self, el):
|
||||
text = six.text_type(el) or ''
|
||||
|
||||
# normalize whitespace if we're not inside a preformatted element
|
||||
if not el.find_parent('pre'):
|
||||
text = whitespace_re.sub(' ', text)
|
||||
|
||||
# escape special characters if we're not inside a preformatted or code element
|
||||
if not el.find_parent(['pre', 'code', 'kbd', 'samp']):
|
||||
text = self.escape(text)
|
||||
|
||||
# remove trailing whitespaces if any of the following condition is true:
|
||||
# - current text node is the last node in li
|
||||
# - current text node is followed by an embedded list
|
||||
if (el.parent.name == 'li'
|
||||
and (not el.next_sibling
|
||||
or el.next_sibling.name in ['ul', 'ol'])):
|
||||
text = text.rstrip()
|
||||
|
||||
return text
|
||||
|
||||
def __getattr__(self, attr):
|
||||
# Handle heading levels > 2
|
||||
# Handle headings
|
||||
m = convert_heading_re.match(attr)
|
||||
if m:
|
||||
n = int(m.group(1))
|
||||
|
||||
def convert_tag(el, text):
|
||||
return self.convert_hn(n, el, text)
|
||||
def convert_tag(el, text, convert_as_inline):
|
||||
return self.convert_hn(n, el, text, convert_as_inline)
|
||||
|
||||
convert_tag.__name__ = 'convert_h%s' % n
|
||||
setattr(self, convert_tag.__name__, convert_tag)
|
||||
@@ -60,62 +195,239 @@ class MarkdownConverter(object):
|
||||
|
||||
def should_convert_tag(self, tag):
|
||||
tag = tag.lower()
|
||||
if self.tags_to_strip is not None:
|
||||
return tag not in self.tags_to_strip
|
||||
elif self.tags_to_convert is not None:
|
||||
return tag in self.tags_to_convert
|
||||
strip = self.options['strip']
|
||||
convert = self.options['convert']
|
||||
if strip is not None:
|
||||
return tag not in strip
|
||||
elif convert is not None:
|
||||
return tag in convert
|
||||
else:
|
||||
return True
|
||||
|
||||
def escape(self, text):
|
||||
if not text:
|
||||
return ''
|
||||
if self.options['escape_misc']:
|
||||
text = re.sub(r'([\\&<`[>~#=+|-])', r'\\\1', text)
|
||||
text = re.sub(r'([0-9])([.)])', r'\1\\\2', text)
|
||||
if self.options['escape_asterisks']:
|
||||
text = text.replace('*', r'\*')
|
||||
if self.options['escape_underscores']:
|
||||
text = text.replace('_', r'\_')
|
||||
return text
|
||||
|
||||
def indent(self, text, level):
|
||||
return line_beginning_re.sub('\t' * level, text) if text else ''
|
||||
|
||||
def underline(self, text, pad_char):
|
||||
text = (text or '').rstrip()
|
||||
return '%s\n%s\n\n' % (text, pad_char * len(text)) if text else ''
|
||||
|
||||
def convert_a(self, el, text):
|
||||
def convert_a(self, el, text, convert_as_inline):
|
||||
prefix, suffix, text = chomp(text)
|
||||
if not text:
|
||||
return ''
|
||||
href = el.get('href')
|
||||
title = el.get('title')
|
||||
# For the replacement see #29: text nodes underscores are escaped
|
||||
if (self.options['autolinks']
|
||||
and text.replace(r'\_', '_') == href
|
||||
and not title
|
||||
and not self.options['default_title']):
|
||||
# Shortcut syntax
|
||||
return '<%s>' % href
|
||||
if self.options['default_title'] and not title:
|
||||
title = href
|
||||
title_part = ' "%s"' % title.replace('"', r'\"') if title else ''
|
||||
return '[%s](%s%s)' % (text or '', href, title_part) if href else text or ''
|
||||
return '%s[%s](%s%s)%s' % (prefix, text, href, title_part, suffix) if href else text
|
||||
|
||||
def convert_b(self, el, text):
|
||||
return self.convert_strong(el, text)
|
||||
convert_b = abstract_inline_conversion(lambda self: 2 * self.options['strong_em_symbol'])
|
||||
|
||||
def convert_blockquote(self, el, text):
|
||||
return '\n' + line_beginning_re.sub('> ', text) if text else ''
|
||||
def convert_blockquote(self, el, text, convert_as_inline):
|
||||
|
||||
def convert_br(self, el, text):
|
||||
return ' \n'
|
||||
if convert_as_inline:
|
||||
return text
|
||||
|
||||
def convert_em(self, el, text):
|
||||
return '*%s*' % text if text else ''
|
||||
return '\n' + (line_beginning_re.sub('> ', text.strip()) + '\n\n') if text else ''
|
||||
|
||||
def convert_h1(self, el, text):
|
||||
return self.underline(text, '=')
|
||||
def convert_br(self, el, text, convert_as_inline):
|
||||
if convert_as_inline:
|
||||
return ""
|
||||
|
||||
def convert_h2(self, el, text):
|
||||
return self.underline(text, '-')
|
||||
|
||||
def convert_hn(self, n, el, text):
|
||||
return '%s %s\n\n' % ('#' * n, text.rstrip()) if text else ''
|
||||
|
||||
def convert_i(self, el, text):
|
||||
return self.convert_em(el, text)
|
||||
|
||||
def convert_li(self, el, text):
|
||||
parent = el.getparent()
|
||||
if parent is not None and parent.tag == 'ol':
|
||||
bullet = '%s.' % (parent.index(el) + 1)
|
||||
if self.options['newline_style'].lower() == BACKSLASH:
|
||||
return '\\\n'
|
||||
else:
|
||||
bullet = '*'
|
||||
return '%s %s\n' % (bullet, text or '')
|
||||
return ' \n'
|
||||
|
||||
def convert_p(self, el, text):
|
||||
def convert_code(self, el, text, convert_as_inline):
|
||||
if el.parent.name == 'pre':
|
||||
return text
|
||||
converter = abstract_inline_conversion(lambda self: '`')
|
||||
return converter(self, el, text, convert_as_inline)
|
||||
|
||||
convert_del = abstract_inline_conversion(lambda self: '~~')
|
||||
|
||||
convert_em = abstract_inline_conversion(lambda self: self.options['strong_em_symbol'])
|
||||
|
||||
convert_kbd = convert_code
|
||||
|
||||
def convert_hn(self, n, el, text, convert_as_inline):
|
||||
if convert_as_inline:
|
||||
return text
|
||||
|
||||
style = self.options['heading_style'].lower()
|
||||
text = text.strip()
|
||||
if style == UNDERLINED and n <= 2:
|
||||
line = '=' if n == 1 else '-'
|
||||
return self.underline(text, line)
|
||||
hashes = '#' * n
|
||||
if style == ATX_CLOSED:
|
||||
return '%s %s %s\n\n' % (hashes, text, hashes)
|
||||
return '%s %s\n\n' % (hashes, text)
|
||||
|
||||
def convert_hr(self, el, text, convert_as_inline):
|
||||
return '\n\n---\n\n'
|
||||
|
||||
convert_i = convert_em
|
||||
|
||||
def convert_img(self, el, text, convert_as_inline):
|
||||
alt = el.attrs.get('alt', None) or ''
|
||||
src = el.attrs.get('src', None) or ''
|
||||
title = el.attrs.get('title', None) or ''
|
||||
title_part = ' "%s"' % title.replace('"', r'\"') if title else ''
|
||||
if (convert_as_inline
|
||||
and el.parent.name not in self.options['keep_inline_images_in']):
|
||||
return alt
|
||||
|
||||
return '' % (alt, src, title_part)
|
||||
|
||||
def convert_list(self, el, text, convert_as_inline):
|
||||
|
||||
# Converting a list to inline is undefined.
|
||||
# Ignoring convert_to_inline for list.
|
||||
|
||||
nested = False
|
||||
before_paragraph = False
|
||||
if el.next_sibling and el.next_sibling.name not in ['ul', 'ol']:
|
||||
before_paragraph = True
|
||||
while el:
|
||||
if el.name == 'li':
|
||||
nested = True
|
||||
break
|
||||
el = el.parent
|
||||
if nested:
|
||||
# remove trailing newline if nested
|
||||
return '\n' + self.indent(text, 1).rstrip()
|
||||
return text + ('\n' if before_paragraph else '')
|
||||
|
||||
convert_ul = convert_list
|
||||
convert_ol = convert_list
|
||||
|
||||
def convert_li(self, el, text, convert_as_inline):
|
||||
parent = el.parent
|
||||
if parent is not None and parent.name == 'ol':
|
||||
if parent.get("start") and str(parent.get("start")).isnumeric():
|
||||
start = int(parent.get("start"))
|
||||
else:
|
||||
start = 1
|
||||
bullet = '%s.' % (start + parent.index(el))
|
||||
else:
|
||||
depth = -1
|
||||
while el:
|
||||
if el.name == 'ul':
|
||||
depth += 1
|
||||
el = el.parent
|
||||
bullets = self.options['bullets']
|
||||
bullet = bullets[depth % len(bullets)]
|
||||
return '%s %s\n' % (bullet, (text or '').strip())
|
||||
|
||||
def convert_p(self, el, text, convert_as_inline):
|
||||
if convert_as_inline:
|
||||
return text
|
||||
if self.options['wrap']:
|
||||
text = fill(text,
|
||||
width=self.options['wrap_width'],
|
||||
break_long_words=False,
|
||||
break_on_hyphens=False)
|
||||
return '%s\n\n' % text if text else ''
|
||||
|
||||
def convert_strong(self, el, text):
|
||||
return '**%s**' % text if text else ''
|
||||
def convert_pre(self, el, text, convert_as_inline):
|
||||
if not text:
|
||||
return ''
|
||||
code_language = self.options['code_language']
|
||||
|
||||
if self.options['code_language_callback']:
|
||||
code_language = self.options['code_language_callback'](el) or code_language
|
||||
|
||||
return '\n```%s\n%s\n```\n' % (code_language, text)
|
||||
|
||||
def convert_script(self, el, text, convert_as_inline):
|
||||
return ''
|
||||
|
||||
def convert_style(self, el, text, convert_as_inline):
|
||||
return ''
|
||||
|
||||
convert_s = convert_del
|
||||
|
||||
convert_strong = convert_b
|
||||
|
||||
convert_samp = convert_code
|
||||
|
||||
convert_sub = abstract_inline_conversion(lambda self: self.options['sub_symbol'])
|
||||
|
||||
convert_sup = abstract_inline_conversion(lambda self: self.options['sup_symbol'])
|
||||
|
||||
def convert_table(self, el, text, convert_as_inline):
|
||||
return '\n\n' + text + '\n'
|
||||
|
||||
def convert_caption(self, el, text, convert_as_inline):
|
||||
return text + '\n'
|
||||
|
||||
def convert_figcaption(self, el, text, convert_as_inline):
|
||||
return '\n\n' + text + '\n\n'
|
||||
|
||||
def convert_td(self, el, text, convert_as_inline):
|
||||
colspan = 1
|
||||
if 'colspan' in el.attrs and el['colspan'].isdigit():
|
||||
colspan = int(el['colspan'])
|
||||
return ' ' + text.strip().replace("\n", " ") + ' |' * colspan
|
||||
|
||||
def convert_th(self, el, text, convert_as_inline):
|
||||
colspan = 1
|
||||
if 'colspan' in el.attrs and el['colspan'].isdigit():
|
||||
colspan = int(el['colspan'])
|
||||
return ' ' + text.strip().replace("\n", " ") + ' |' * colspan
|
||||
|
||||
def convert_tr(self, el, text, convert_as_inline):
|
||||
cells = el.find_all(['td', 'th'])
|
||||
is_headrow = (
|
||||
all([cell.name == 'th' for cell in cells])
|
||||
or (not el.previous_sibling and not el.parent.name == 'tbody')
|
||||
or (not el.previous_sibling and el.parent.name == 'tbody' and len(el.parent.parent.find_all(['thead'])) < 1)
|
||||
)
|
||||
overline = ''
|
||||
underline = ''
|
||||
if is_headrow and not el.previous_sibling:
|
||||
# first row and is headline: print headline underline
|
||||
full_colspan = 0
|
||||
for cell in cells:
|
||||
if 'colspan' in cell.attrs and cell['colspan'].isdigit():
|
||||
full_colspan += int(cell["colspan"])
|
||||
else:
|
||||
full_colspan += 1
|
||||
underline += '| ' + ' | '.join(['---'] * full_colspan) + ' |' + '\n'
|
||||
elif (not el.previous_sibling
|
||||
and (el.parent.name == 'table'
|
||||
or (el.parent.name == 'tbody'
|
||||
and not el.parent.previous_sibling))):
|
||||
# first row, not headline, and:
|
||||
# - the parent is table or
|
||||
# - the parent is tbody at the beginning of a table.
|
||||
# print empty headline above this row
|
||||
overline += '| ' + ' | '.join([''] * len(cells)) + ' |' + '\n'
|
||||
overline += '| ' + ' | '.join(['---'] * len(cells)) + ' |' + '\n'
|
||||
return overline + '|' + text + '\n' + underline
|
||||
|
||||
|
||||
def markdownify(html, strip=None, convert=None):
|
||||
converter = MarkdownConverter(strip, convert)
|
||||
return converter.convert(html)
|
||||
def markdownify(html, **options):
|
||||
return MarkdownConverter(**options).convert(html)
|
||||
|
||||
73
markdownify/main.py
Normal file
73
markdownify/main.py
Normal file
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from markdownify import markdownify, ATX, ATX_CLOSED, UNDERLINED, \
|
||||
SPACES, BACKSLASH, ASTERISK, UNDERSCORE
|
||||
|
||||
|
||||
def main(argv=sys.argv[1:]):
|
||||
parser = argparse.ArgumentParser(
|
||||
prog='markdownify',
|
||||
description='Converts html to markdown.',
|
||||
)
|
||||
|
||||
parser.add_argument('html', nargs='?', type=argparse.FileType('r'),
|
||||
default=sys.stdin,
|
||||
help="The html file to convert. Defaults to STDIN if not "
|
||||
"provided.")
|
||||
parser.add_argument('-s', '--strip', nargs='*',
|
||||
help="A list of tags to strip. This option can't be used with "
|
||||
"the --convert option.")
|
||||
parser.add_argument('-c', '--convert', nargs='*',
|
||||
help="A list of tags to convert. This option can't be used with "
|
||||
"the --strip option.")
|
||||
parser.add_argument('-a', '--autolinks', action='store_true',
|
||||
help="A boolean indicating whether the 'automatic link' style "
|
||||
"should be used when a 'a' tag's contents match its href.")
|
||||
parser.add_argument('--default-title', action='store_false',
|
||||
help="A boolean to enable setting the title of a link to its "
|
||||
"href, if no title is given.")
|
||||
parser.add_argument('--heading-style', default=UNDERLINED,
|
||||
choices=(ATX, ATX_CLOSED, UNDERLINED),
|
||||
help="Defines how headings should be converted.")
|
||||
parser.add_argument('-b', '--bullets', default='*+-',
|
||||
help="A string of bullet styles to use; the bullet will "
|
||||
"alternate based on nesting level.")
|
||||
parser.add_argument('--strong-em-symbol', default=ASTERISK,
|
||||
choices=(ASTERISK, UNDERSCORE),
|
||||
help="Use * or _ to convert strong and italics text"),
|
||||
parser.add_argument('--sub-symbol', default='',
|
||||
help="Define the chars that surround '<sub>'.")
|
||||
parser.add_argument('--sup-symbol', default='',
|
||||
help="Define the chars that surround '<sup>'.")
|
||||
parser.add_argument('--newline-style', default=SPACES,
|
||||
choices=(SPACES, BACKSLASH),
|
||||
help="Defines the style of <br> conversions: two spaces "
|
||||
"or backslash at the and of the line thet should break.")
|
||||
parser.add_argument('--code-language', default='',
|
||||
help="Defines the language that should be assumed for all "
|
||||
"'<pre>' sections.")
|
||||
parser.add_argument('--no-escape-asterisks', dest='escape_asterisks',
|
||||
action='store_false',
|
||||
help="Do not escape '*' to '\\*' in text.")
|
||||
parser.add_argument('--no-escape-underscores', dest='escape_underscores',
|
||||
action='store_false',
|
||||
help="Do not escape '_' to '\\_' in text.")
|
||||
parser.add_argument('-i', '--keep-inline-images-in', nargs='*',
|
||||
help="Images are converted to their alt-text when the images are "
|
||||
"located inside headlines or table cells. If some inline images "
|
||||
"should be converted to markdown images instead, this option can "
|
||||
"be set to a list of parent tags that should be allowed to "
|
||||
"contain inline images.")
|
||||
parser.add_argument('-w', '--wrap', action='store_true',
|
||||
help="Wrap all text paragraphs at --wrap-width characters.")
|
||||
parser.add_argument('--wrap-width', type=int, default=80)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
print(markdownify(**vars(args)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,8 +0,0 @@
|
||||
pkgmeta = dict(
|
||||
__title__='markdownify',
|
||||
__author__='Matthew Tretter',
|
||||
__version__='0.2.0',
|
||||
)
|
||||
|
||||
globals().update(pkgmeta)
|
||||
__all__ = pkgmeta.keys()
|
||||
45
pyproject.toml
Normal file
45
pyproject.toml
Normal file
@@ -0,0 +1,45 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=61.2", "setuptools_scm[toml]>=3.4.3"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "markdownify"
|
||||
version = "0.13.0"
|
||||
authors = [{name = "Matthew Tretter", email = "m@tthewwithanm.com"}]
|
||||
description = "Convert HTML to markdown."
|
||||
readme = "README.rst"
|
||||
classifiers = [
|
||||
"Environment :: Web Environment",
|
||||
"Framework :: Django",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 2.5",
|
||||
"Programming Language :: Python :: 2.6",
|
||||
"Programming Language :: Python :: 2.7",
|
||||
"Programming Language :: Python :: 3.6",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Topic :: Utilities",
|
||||
]
|
||||
dependencies = [
|
||||
"beautifulsoup4>=4.9,<5",
|
||||
"six>=1.15,<2"
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "http://github.com/matthewwithanm/python-markdownify"
|
||||
Download = "http://github.com/matthewwithanm/python-markdownify/tarball/master"
|
||||
|
||||
[project.scripts]
|
||||
markdownify = "markdownify.main:main"
|
||||
|
||||
[tool.setuptools]
|
||||
zip-safe = false
|
||||
include-package-data = true
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["markdownify", "markdownify.*"]
|
||||
namespaces = false
|
||||
|
||||
[tool.setuptools_scm]
|
||||
62
setup.py
62
setup.py
@@ -1,62 +0,0 @@
|
||||
#/usr/bin/env python
|
||||
import codecs
|
||||
import os
|
||||
from setuptools import setup, find_packages
|
||||
from setuptools.command.test import test as TestCommand
|
||||
|
||||
|
||||
read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read()
|
||||
|
||||
|
||||
pkgmeta = {}
|
||||
execfile(os.path.join(os.path.dirname(__file__), 'markdownify', 'pkgmeta.py'),
|
||||
pkgmeta)
|
||||
|
||||
|
||||
class PyTest(TestCommand):
|
||||
def finalize_options(self):
|
||||
TestCommand.finalize_options(self)
|
||||
self.test_args = ['tests', '-s']
|
||||
self.test_suite = True
|
||||
|
||||
def run_tests(self):
|
||||
import pytest
|
||||
errno = pytest.main(self.test_args)
|
||||
raise SystemExit(errno)
|
||||
|
||||
|
||||
setup(
|
||||
name='markdownify',
|
||||
description='Convert HTML to markdown.',
|
||||
long_description=read(os.path.join(os.path.dirname(__file__), 'README.rst')),
|
||||
version=pkgmeta['__version__'],
|
||||
author=pkgmeta['__author__'],
|
||||
author_email='m@tthewwithanm.com',
|
||||
url='http://github.com/matthewwithanm/python-markdownify',
|
||||
download_url='http://github.com/matthewwithanm/python-markdownify/tarball/master',
|
||||
packages=find_packages(),
|
||||
zip_safe=False,
|
||||
include_package_data=True,
|
||||
tests_require=[
|
||||
'pytest',
|
||||
],
|
||||
install_requires=[
|
||||
'lxml',
|
||||
'BeautifulSoup',
|
||||
],
|
||||
classifiers=[
|
||||
'Environment :: Web Environment',
|
||||
'Framework :: Django',
|
||||
'Intended Audience :: Developers',
|
||||
'License :: OSI Approved :: BSD License',
|
||||
'Operating System :: OS Independent',
|
||||
'Programming Language :: Python :: 2.5',
|
||||
'Programming Language :: Python :: 2.6',
|
||||
'Programming Language :: Python :: 2.7',
|
||||
'Topic :: Utilities'
|
||||
],
|
||||
setup_requires=[],
|
||||
cmdclass={
|
||||
'test': PyTest,
|
||||
},
|
||||
)
|
||||
10
shell.nix
Normal file
10
shell.nix
Normal file
@@ -0,0 +1,10 @@
|
||||
{ pkgs ? import <nixpkgs> {} }:
|
||||
pkgs.mkShell {
|
||||
name = "python-shell";
|
||||
buildInputs = with pkgs; [
|
||||
python38
|
||||
python38Packages.tox
|
||||
python38Packages.setuptools
|
||||
python38Packages.virtualenv
|
||||
];
|
||||
}
|
||||
@@ -1,6 +1,39 @@
|
||||
from markdownify import markdownify as md
|
||||
|
||||
|
||||
def test_chomp():
|
||||
assert md(' <b></b> ') == ' '
|
||||
assert md(' <b> </b> ') == ' '
|
||||
assert md(' <b> </b> ') == ' '
|
||||
assert md(' <b> </b> ') == ' '
|
||||
assert md(' <b>s </b> ') == ' **s** '
|
||||
assert md(' <b> s</b> ') == ' **s** '
|
||||
assert md(' <b> s </b> ') == ' **s** '
|
||||
assert md(' <b> s </b> ') == ' **s** '
|
||||
|
||||
|
||||
def test_nested():
|
||||
text = md('<p>This is an <a href="http://example.com/">example link</a>.</p>')
|
||||
assert text == 'This is an [example link](http://example.com/).\n\n'
|
||||
|
||||
|
||||
def test_ignore_comments():
|
||||
text = md("<!-- This is a comment -->")
|
||||
assert text == ""
|
||||
|
||||
|
||||
def test_ignore_comments_with_other_tags():
|
||||
text = md("<!-- This is a comment --><a href='http://example.com/'>example link</a>")
|
||||
assert text == "[example link](http://example.com/)"
|
||||
|
||||
|
||||
def test_code_with_tricky_content():
|
||||
assert md('<code>></code>') == "`>`"
|
||||
assert md('<code>/home/</code><b>username</b>') == "`/home/`**username**"
|
||||
assert md('First line <code>blah blah<br />blah blah</code> second line') \
|
||||
== "First line `blah blah \nblah blah` second line"
|
||||
|
||||
|
||||
def test_special_tags():
|
||||
assert md('<!DOCTYPE html>') == ''
|
||||
assert md('<![CDATA[foobar]]>') == 'foobar'
|
||||
|
||||
@@ -10,4 +10,4 @@ def test_soup():
|
||||
|
||||
|
||||
def test_whitespace():
|
||||
assert md(' a b \n\n c ') == ' a b c '
|
||||
assert md(' a b \t\t c ') == ' a b c '
|
||||
|
||||
@@ -1,34 +1,122 @@
|
||||
from markdownify import markdownify as md
|
||||
from markdownify import markdownify as md, ATX, ATX_CLOSED, BACKSLASH, UNDERSCORE
|
||||
|
||||
|
||||
def inline_tests(tag, markup):
|
||||
# test template for different inline tags
|
||||
assert md(f'<{tag}>Hello</{tag}>') == f'{markup}Hello{markup}'
|
||||
assert md(f'foo <{tag}>Hello</{tag}> bar') == f'foo {markup}Hello{markup} bar'
|
||||
assert md(f'foo<{tag}> Hello</{tag}> bar') == f'foo {markup}Hello{markup} bar'
|
||||
assert md(f'foo <{tag}>Hello </{tag}>bar') == f'foo {markup}Hello{markup} bar'
|
||||
assert md(f'foo <{tag}></{tag}> bar') in ['foo bar', 'foo bar'] # Either is OK
|
||||
|
||||
|
||||
def test_a():
|
||||
assert md('<a href="http://google.com">Google</a>') == '[Google](http://google.com)'
|
||||
assert md('<a href="https://google.com">Google</a>') == '[Google](https://google.com)'
|
||||
assert md('<a href="https://google.com">https://google.com</a>') == '<https://google.com>'
|
||||
assert md('<a href="https://community.kde.org/Get_Involved">https://community.kde.org/Get_Involved</a>') == '<https://community.kde.org/Get_Involved>'
|
||||
assert md('<a href="https://community.kde.org/Get_Involved">https://community.kde.org/Get_Involved</a>', autolinks=False) == '[https://community.kde.org/Get\\_Involved](https://community.kde.org/Get_Involved)'
|
||||
|
||||
|
||||
def test_a_spaces():
|
||||
assert md('foo <a href="http://google.com">Google</a> bar') == 'foo [Google](http://google.com) bar'
|
||||
assert md('foo<a href="http://google.com"> Google</a> bar') == 'foo [Google](http://google.com) bar'
|
||||
assert md('foo <a href="http://google.com">Google </a>bar') == 'foo [Google](http://google.com) bar'
|
||||
assert md('foo <a href="http://google.com"></a> bar') == 'foo bar'
|
||||
|
||||
|
||||
def test_a_with_title():
|
||||
text = md('<a href="http://google.com" title="The "Goog"">Google</a>')
|
||||
assert text == r'[Google](http://google.com "The \"Goog\"")'
|
||||
assert md('<a href="https://google.com">https://google.com</a>', default_title=True) == '[https://google.com](https://google.com "https://google.com")'
|
||||
|
||||
|
||||
def test_a_shortcut():
|
||||
text = md('<a href="http://google.com">http://google.com</a>')
|
||||
assert text == '<http://google.com>'
|
||||
|
||||
|
||||
def test_a_no_autolinks():
|
||||
assert md('<a href="https://google.com">https://google.com</a>', autolinks=False) == '[https://google.com](https://google.com)'
|
||||
|
||||
|
||||
def test_b():
|
||||
assert md('<b>Hello</b>') == '**Hello**'
|
||||
|
||||
|
||||
def test_b_spaces():
|
||||
assert md('foo <b>Hello</b> bar') == 'foo **Hello** bar'
|
||||
assert md('foo<b> Hello</b> bar') == 'foo **Hello** bar'
|
||||
assert md('foo <b>Hello </b>bar') == 'foo **Hello** bar'
|
||||
assert md('foo <b></b> bar') == 'foo bar'
|
||||
|
||||
|
||||
def test_blockquote():
|
||||
assert md('<blockquote>Hello</blockquote>').strip() == '> Hello'
|
||||
assert md('<blockquote>Hello</blockquote>') == '\n> Hello\n\n'
|
||||
assert md('<blockquote>\nHello\n</blockquote>') == '\n> Hello\n\n'
|
||||
|
||||
|
||||
def test_nested_blockquote():
|
||||
text = md('<blockquote>And she was like <blockquote>Hello</blockquote></blockquote>').strip()
|
||||
assert text == '> And she was like \n> > Hello'
|
||||
def test_blockquote_with_nested_paragraph():
|
||||
assert md('<blockquote><p>Hello</p></blockquote>') == '\n> Hello\n\n'
|
||||
assert md('<blockquote><p>Hello</p><p>Hello again</p></blockquote>') == '\n> Hello\n> \n> Hello again\n\n'
|
||||
|
||||
|
||||
def test_blockquote_with_paragraph():
|
||||
assert md('<blockquote>Hello</blockquote><p>handsome</p>') == '\n> Hello\n\nhandsome\n\n'
|
||||
|
||||
|
||||
def test_blockquote_nested():
|
||||
text = md('<blockquote>And she was like <blockquote>Hello</blockquote></blockquote>')
|
||||
assert text == '\n> And she was like \n> > Hello\n\n'
|
||||
|
||||
|
||||
def test_br():
|
||||
assert md('a<br />b<br />c') == 'a \nb \nc'
|
||||
assert md('a<br />b<br />c', newline_style=BACKSLASH) == 'a\\\nb\\\nc'
|
||||
|
||||
|
||||
def test_caption():
|
||||
assert md('TEXT<figure><figcaption>Caption</figcaption><span>SPAN</span></figure>') == 'TEXT\n\nCaption\n\nSPAN'
|
||||
assert md('<figure><span>SPAN</span><figcaption>Caption</figcaption></figure>TEXT') == 'SPAN\n\nCaption\n\nTEXT'
|
||||
|
||||
|
||||
def test_code():
|
||||
inline_tests('code', '`')
|
||||
assert md('<code>*this_should_not_escape*</code>') == '`*this_should_not_escape*`'
|
||||
assert md('<kbd>*this_should_not_escape*</kbd>') == '`*this_should_not_escape*`'
|
||||
assert md('<samp>*this_should_not_escape*</samp>') == '`*this_should_not_escape*`'
|
||||
assert md('<code><span>*this_should_not_escape*</span></code>') == '`*this_should_not_escape*`'
|
||||
assert md('<code>this should\t\tnormalize</code>') == '`this should normalize`'
|
||||
assert md('<code><span>this should\t\tnormalize</span></code>') == '`this should normalize`'
|
||||
assert md('<code>foo<b>bar</b>baz</code>') == '`foobarbaz`'
|
||||
assert md('<kbd>foo<i>bar</i>baz</kbd>') == '`foobarbaz`'
|
||||
assert md('<samp>foo<del> bar </del>baz</samp>') == '`foo bar baz`'
|
||||
assert md('<samp>foo <del>bar</del> baz</samp>') == '`foo bar baz`'
|
||||
assert md('<code>foo<em> bar </em>baz</code>') == '`foo bar baz`'
|
||||
assert md('<code>foo<code> bar </code>baz</code>') == '`foo bar baz`'
|
||||
assert md('<code>foo<strong> bar </strong>baz</code>') == '`foo bar baz`'
|
||||
assert md('<code>foo<s> bar </s>baz</code>') == '`foo bar baz`'
|
||||
assert md('<code>foo<sup>bar</sup>baz</code>', sup_symbol='^') == '`foobarbaz`'
|
||||
assert md('<code>foo<sub>bar</sub>baz</code>', sub_symbol='^') == '`foobarbaz`'
|
||||
|
||||
|
||||
def test_del():
|
||||
inline_tests('del', '~~')
|
||||
|
||||
|
||||
def test_div():
|
||||
assert md('Hello</div> World') == 'Hello World'
|
||||
|
||||
|
||||
def test_em():
|
||||
assert md('<em>Hello</em>') == '*Hello*'
|
||||
inline_tests('em', '*')
|
||||
|
||||
|
||||
def test_header_with_space():
|
||||
assert md('<h3>\n\nHello</h3>') == '### Hello\n\n'
|
||||
assert md('<h4>\n\nHello</h4>') == '#### Hello\n\n'
|
||||
assert md('<h5>\n\nHello</h5>') == '##### Hello\n\n'
|
||||
assert md('<h5>\n\nHello\n\n</h5>') == '##### Hello\n\n'
|
||||
assert md('<h5>\n\nHello \n\n</h5>') == '##### Hello\n\n'
|
||||
|
||||
|
||||
def test_h1():
|
||||
@@ -41,24 +129,163 @@ def test_h2():
|
||||
|
||||
def test_hn():
|
||||
assert md('<h3>Hello</h3>') == '### Hello\n\n'
|
||||
assert md('<h4>Hello</h4>') == '#### Hello\n\n'
|
||||
assert md('<h5>Hello</h5>') == '##### Hello\n\n'
|
||||
assert md('<h6>Hello</h6>') == '###### Hello\n\n'
|
||||
|
||||
|
||||
def test_hn_chained():
|
||||
assert md('<h1>First</h1>\n<h2>Second</h2>\n<h3>Third</h3>', heading_style=ATX) == '# First\n\n\n## Second\n\n\n### Third\n\n'
|
||||
assert md('X<h1>First</h1>', heading_style=ATX) == 'X# First\n\n'
|
||||
|
||||
|
||||
def test_hn_nested_tag_heading_style():
|
||||
assert md('<h1>A <p>P</p> C </h1>', heading_style=ATX_CLOSED) == '# A P C #\n\n'
|
||||
assert md('<h1>A <p>P</p> C </h1>', heading_style=ATX) == '# A P C\n\n'
|
||||
|
||||
|
||||
def test_hn_nested_simple_tag():
|
||||
tag_to_markdown = [
|
||||
("strong", "**strong**"),
|
||||
("b", "**b**"),
|
||||
("em", "*em*"),
|
||||
("i", "*i*"),
|
||||
("p", "p"),
|
||||
("a", "a"),
|
||||
("div", "div"),
|
||||
("blockquote", "blockquote"),
|
||||
]
|
||||
|
||||
for tag, markdown in tag_to_markdown:
|
||||
assert md('<h3>A <' + tag + '>' + tag + '</' + tag + '> B</h3>') == '### A ' + markdown + ' B\n\n'
|
||||
|
||||
assert md('<h3>A <br>B</h3>', heading_style=ATX) == '### A B\n\n'
|
||||
|
||||
# Nested lists not supported
|
||||
# assert md('<h3>A <ul><li>li1</i><li>l2</li></ul></h3>', heading_style=ATX) == '### A li1 li2 B\n\n'
|
||||
|
||||
|
||||
def test_hn_nested_img():
|
||||
image_attributes_to_markdown = [
|
||||
("", "", ""),
|
||||
("alt='Alt Text'", "Alt Text", ""),
|
||||
("alt='Alt Text' title='Optional title'", "Alt Text", " \"Optional title\""),
|
||||
]
|
||||
for image_attributes, markdown, title in image_attributes_to_markdown:
|
||||
assert md('<h3>A <img src="/path/to/img.jpg" ' + image_attributes + '/> B</h3>') == '### A ' + markdown + ' B\n\n'
|
||||
assert md('<h3>A <img src="/path/to/img.jpg" ' + image_attributes + '/> B</h3>', keep_inline_images_in=['h3']) == '### A  B\n\n'
|
||||
|
||||
|
||||
def test_hn_atx_headings():
|
||||
assert md('<h1>Hello</h1>', heading_style=ATX) == '# Hello\n\n'
|
||||
assert md('<h2>Hello</h2>', heading_style=ATX) == '## Hello\n\n'
|
||||
|
||||
|
||||
def test_hn_atx_closed_headings():
|
||||
assert md('<h1>Hello</h1>', heading_style=ATX_CLOSED) == '# Hello #\n\n'
|
||||
assert md('<h2>Hello</h2>', heading_style=ATX_CLOSED) == '## Hello ##\n\n'
|
||||
|
||||
|
||||
def test_head():
|
||||
assert md('<head>head</head>') == 'head'
|
||||
|
||||
|
||||
def test_hr():
|
||||
assert md('Hello<hr>World') == 'Hello\n\n---\n\nWorld'
|
||||
assert md('Hello<hr />World') == 'Hello\n\n---\n\nWorld'
|
||||
assert md('<p>Hello</p>\n<hr>\n<p>World</p>') == 'Hello\n\n\n\n\n---\n\n\nWorld\n\n'
|
||||
|
||||
|
||||
def test_i():
|
||||
assert md('<i>Hello</i>') == '*Hello*'
|
||||
|
||||
|
||||
def test_ol():
|
||||
assert md('<ol><li>a</li><li>b</li></ol>') == '1. a\n2. b\n'
|
||||
def test_img():
|
||||
assert md('<img src="/path/to/img.jpg" alt="Alt text" title="Optional title" />') == ''
|
||||
assert md('<img src="/path/to/img.jpg" alt="Alt text" />') == ''
|
||||
|
||||
|
||||
def test_kbd():
|
||||
inline_tests('kbd', '`')
|
||||
|
||||
|
||||
def test_p():
|
||||
assert md('<p>hello</p>') == 'hello\n\n'
|
||||
assert md('<p>123456789 123456789</p>') == '123456789 123456789\n\n'
|
||||
assert md('<p>123456789 123456789</p>', wrap=True, wrap_width=10) == '123456789\n123456789\n\n'
|
||||
assert md('<p><a href="https://example.com">Some long link</a></p>', wrap=True, wrap_width=10) == '[Some long\nlink](https://example.com)\n\n'
|
||||
assert md('<p>12345<br />67890</p>', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '12345\\\n67890\n\n'
|
||||
assert md('<p>12345678901<br />12345</p>', wrap=True, wrap_width=10, newline_style=BACKSLASH) == '12345678901\\\n12345\n\n'
|
||||
|
||||
|
||||
def test_pre():
|
||||
assert md('<pre>test\n foo\nbar</pre>') == '\n```\ntest\n foo\nbar\n```\n'
|
||||
assert md('<pre><code>test\n foo\nbar</code></pre>') == '\n```\ntest\n foo\nbar\n```\n'
|
||||
assert md('<pre>*this_should_not_escape*</pre>') == '\n```\n*this_should_not_escape*\n```\n'
|
||||
assert md('<pre><span>*this_should_not_escape*</span></pre>') == '\n```\n*this_should_not_escape*\n```\n'
|
||||
assert md('<pre>\t\tthis should\t\tnot normalize</pre>') == '\n```\n\t\tthis should\t\tnot normalize\n```\n'
|
||||
assert md('<pre><span>\t\tthis should\t\tnot normalize</span></pre>') == '\n```\n\t\tthis should\t\tnot normalize\n```\n'
|
||||
assert md('<pre>foo<b>\nbar\n</b>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
|
||||
assert md('<pre>foo<i>\nbar\n</i>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
|
||||
assert md('<pre>foo\n<i>bar</i>\nbaz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
|
||||
assert md('<pre>foo<i>\n</i>baz</pre>') == '\n```\nfoo\nbaz\n```\n'
|
||||
assert md('<pre>foo<del>\nbar\n</del>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
|
||||
assert md('<pre>foo<em>\nbar\n</em>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
|
||||
assert md('<pre>foo<code>\nbar\n</code>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
|
||||
assert md('<pre>foo<strong>\nbar\n</strong>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
|
||||
assert md('<pre>foo<s>\nbar\n</s>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
|
||||
assert md('<pre>foo<sup>\nbar\n</sup>baz</pre>', sup_symbol='^') == '\n```\nfoo\nbar\nbaz\n```\n'
|
||||
assert md('<pre>foo<sub>\nbar\n</sub>baz</pre>', sub_symbol='^') == '\n```\nfoo\nbar\nbaz\n```\n'
|
||||
|
||||
|
||||
def test_script():
|
||||
assert md('foo <script>var foo=42;</script> bar') == 'foo bar'
|
||||
|
||||
|
||||
def test_style():
|
||||
assert md('foo <style>h1 { font-size: larger }</style> bar') == 'foo bar'
|
||||
|
||||
|
||||
def test_s():
|
||||
inline_tests('s', '~~')
|
||||
|
||||
|
||||
def test_samp():
|
||||
inline_tests('samp', '`')
|
||||
|
||||
|
||||
def test_strong():
|
||||
assert md('<strong>Hello</strong>') == '**Hello**'
|
||||
|
||||
|
||||
def test_ul():
|
||||
assert md('<ul><li>a</li><li>b</li></ul>') == '* a\n* b\n'
|
||||
def test_strong_em_symbol():
|
||||
assert md('<strong>Hello</strong>', strong_em_symbol=UNDERSCORE) == '__Hello__'
|
||||
assert md('<b>Hello</b>', strong_em_symbol=UNDERSCORE) == '__Hello__'
|
||||
assert md('<em>Hello</em>', strong_em_symbol=UNDERSCORE) == '_Hello_'
|
||||
assert md('<i>Hello</i>', strong_em_symbol=UNDERSCORE) == '_Hello_'
|
||||
|
||||
|
||||
def test_sub():
|
||||
assert md('<sub>foo</sub>') == 'foo'
|
||||
assert md('<sub>foo</sub>', sub_symbol='~') == '~foo~'
|
||||
assert md('<sub>foo</sub>', sub_symbol='<sub>') == '<sub>foo</sub>'
|
||||
|
||||
|
||||
def test_sup():
|
||||
assert md('<sup>foo</sup>') == 'foo'
|
||||
assert md('<sup>foo</sup>', sup_symbol='^') == '^foo^'
|
||||
assert md('<sup>foo</sup>', sup_symbol='<sup>') == '<sup>foo</sup>'
|
||||
|
||||
|
||||
def test_lang():
|
||||
assert md('<pre>test\n foo\nbar</pre>', code_language='python') == '\n```python\ntest\n foo\nbar\n```\n'
|
||||
assert md('<pre><code>test\n foo\nbar</code></pre>', code_language='javascript') == '\n```javascript\ntest\n foo\nbar\n```\n'
|
||||
|
||||
|
||||
def test_lang_callback():
|
||||
def callback(el):
|
||||
return el['class'][0] if el.has_attr('class') else None
|
||||
|
||||
assert md('<pre class="python">test\n foo\nbar</pre>', code_language_callback=callback) == '\n```python\ntest\n foo\nbar\n```\n'
|
||||
assert md('<pre class="javascript"><code>test\n foo\nbar</code></pre>', code_language_callback=callback) == '\n```javascript\ntest\n foo\nbar\n```\n'
|
||||
assert md('<pre class="javascript"><code class="javascript">test\n foo\nbar</code></pre>', code_language_callback=callback) == '\n```javascript\ntest\n foo\nbar\n```\n'
|
||||
|
||||
25
tests/test_custom_converter.py
Normal file
25
tests/test_custom_converter.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from markdownify import MarkdownConverter
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
|
||||
class ImageBlockConverter(MarkdownConverter):
|
||||
"""
|
||||
Create a custom MarkdownConverter that adds two newlines after an image
|
||||
"""
|
||||
def convert_img(self, el, text, convert_as_inline):
|
||||
return super().convert_img(el, text, convert_as_inline) + '\n\n'
|
||||
|
||||
|
||||
def test_img():
|
||||
# Create shorthand method for conversion
|
||||
def md(html, **options):
|
||||
return ImageBlockConverter(**options).convert(html)
|
||||
|
||||
assert md('<img src="/path/to/img.jpg" alt="Alt text" title="Optional title" />') == '\n\n'
|
||||
assert md('<img src="/path/to/img.jpg" alt="Alt text" />') == '\n\n'
|
||||
|
||||
|
||||
def test_soup():
|
||||
html = '<b>test</b>'
|
||||
soup = BeautifulSoup(html, 'html.parser')
|
||||
assert MarkdownConverter().convert_soup(soup) == '**test**'
|
||||
@@ -1,12 +1,18 @@
|
||||
from markdownify import markdownify as md
|
||||
|
||||
|
||||
def test_asterisks():
|
||||
assert md('*hey*dude*') == r'\*hey\*dude\*'
|
||||
assert md('*hey*dude*', escape_asterisks=False) == r'*hey*dude*'
|
||||
|
||||
|
||||
def test_underscore():
|
||||
assert md('_hey_dude_') == '\_hey\_dude\_'
|
||||
assert md('_hey_dude_') == r'\_hey\_dude\_'
|
||||
assert md('_hey_dude_', escape_underscores=False) == r'_hey_dude_'
|
||||
|
||||
|
||||
def test_xml_entities():
|
||||
assert md('&') == '&'
|
||||
assert md('&') == r'\&'
|
||||
|
||||
|
||||
def test_named_entities():
|
||||
@@ -19,4 +25,23 @@ def test_hexadecimal_entities():
|
||||
|
||||
|
||||
def test_single_escaping_entities():
|
||||
assert md('&amp;') == '&'
|
||||
assert md('&amp;') == r'\&'
|
||||
|
||||
|
||||
def text_misc():
|
||||
assert md('\\*') == r'\\\*'
|
||||
assert md('<foo>') == r'\<foo\>'
|
||||
assert md('# foo') == r'\# foo'
|
||||
assert md('> foo') == r'\> foo'
|
||||
assert md('~~foo~~') == r'\~\~foo\~\~'
|
||||
assert md('foo\n===\n') == 'foo\n\\=\\=\\=\n'
|
||||
assert md('---\n') == '\\-\\-\\-\n'
|
||||
assert md('+ x\n+ y\n') == '\\+ x\n\\+ y\n'
|
||||
assert md('`x`') == r'\`x\`'
|
||||
assert md('[text](link)') == r'\[text](link)'
|
||||
assert md('1. x') == r'1\. x'
|
||||
assert md('not a number. x') == r'not a number. x'
|
||||
assert md('1) x') == r'1\) x'
|
||||
assert md('not a number) x') == r'not a number) x'
|
||||
assert md('|not table|') == r'\|not table\|'
|
||||
assert md(r'\ <foo> &amp; | ` `', escape_misc=False) == r'\ <foo> & | ` `'
|
||||
|
||||
84
tests/test_lists.py
Normal file
84
tests/test_lists.py
Normal file
@@ -0,0 +1,84 @@
|
||||
from markdownify import markdownify as md
|
||||
|
||||
|
||||
nested_uls = """
|
||||
<ul>
|
||||
<li>1
|
||||
<ul>
|
||||
<li>a
|
||||
<ul>
|
||||
<li>I</li>
|
||||
<li>II</li>
|
||||
<li>III</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>b</li>
|
||||
<li>c</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>2</li>
|
||||
<li>3</li>
|
||||
</ul>"""
|
||||
|
||||
nested_ols = """
|
||||
<ol>
|
||||
<li>1
|
||||
<ol>
|
||||
<li>a
|
||||
<ol>
|
||||
<li>I</li>
|
||||
<li>II</li>
|
||||
<li>III</li>
|
||||
</ol>
|
||||
</li>
|
||||
<li>b</li>
|
||||
<li>c</li>
|
||||
</ol>
|
||||
</li>
|
||||
<li>2</li>
|
||||
<li>3</li>
|
||||
</ul>"""
|
||||
|
||||
|
||||
def test_ol():
|
||||
assert md('<ol><li>a</li><li>b</li></ol>') == '1. a\n2. b\n'
|
||||
assert md('<ol start="3"><li>a</li><li>b</li></ol>') == '3. a\n4. b\n'
|
||||
assert md('<ol start="-1"><li>a</li><li>b</li></ol>') == '1. a\n2. b\n'
|
||||
assert md('<ol start="foo"><li>a</li><li>b</li></ol>') == '1. a\n2. b\n'
|
||||
assert md('<ol start="1.5"><li>a</li><li>b</li></ol>') == '1. a\n2. b\n'
|
||||
|
||||
|
||||
def test_nested_ols():
|
||||
assert md(nested_ols) == '\n1. 1\n\t1. a\n\t\t1. I\n\t\t2. II\n\t\t3. III\n\t2. b\n\t3. c\n2. 2\n3. 3\n'
|
||||
|
||||
|
||||
def test_ul():
|
||||
assert md('<ul><li>a</li><li>b</li></ul>') == '* a\n* b\n'
|
||||
assert md("""<ul>
|
||||
<li>
|
||||
a
|
||||
</li>
|
||||
<li> b </li>
|
||||
<li> c
|
||||
</li>
|
||||
</ul>""") == '* a\n* b\n* c\n'
|
||||
|
||||
|
||||
def test_inline_ul():
|
||||
assert md('<p>foo</p><ul><li>a</li><li>b</li></ul><p>bar</p>') == 'foo\n\n* a\n* b\n\nbar\n\n'
|
||||
|
||||
|
||||
def test_nested_uls():
|
||||
"""
|
||||
Nested ULs should alternate bullet characters.
|
||||
|
||||
"""
|
||||
assert md(nested_uls) == '\n* 1\n\t+ a\n\t\t- I\n\t\t- II\n\t\t- III\n\t+ b\n\t+ c\n* 2\n* 3\n'
|
||||
|
||||
|
||||
def test_bullets():
|
||||
assert md(nested_uls, bullets='-') == '\n- 1\n\t- a\n\t\t- I\n\t\t- II\n\t\t- III\n\t- b\n\t- c\n- 2\n- 3\n'
|
||||
|
||||
|
||||
def test_li_text():
|
||||
assert md('<ul><li>foo <a href="#">bar</a></li><li>foo bar </li><li>foo <b>bar</b> <i>space</i>.</ul>') == '* foo [bar](#)\n* foo bar\n* foo **bar** *space*.\n'
|
||||
254
tests/test_tables.py
Normal file
254
tests/test_tables.py
Normal file
@@ -0,0 +1,254 @@
|
||||
from markdownify import markdownify as md
|
||||
|
||||
|
||||
table = """<table>
|
||||
<tr>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Jill</td>
|
||||
<td>Smith</td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
|
||||
table_with_html_content = """<table>
|
||||
<tr>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>Jill</b></td>
|
||||
<td><i>Smith</i></td>
|
||||
<td><a href="#">50</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
|
||||
table_with_paragraphs = """<table>
|
||||
<tr>
|
||||
<th>Firstname</th>
|
||||
<th><p>Lastname</p></th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><p>Jill</p></td>
|
||||
<td><p>Smith</p></td>
|
||||
<td><p>50</p></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
table_with_linebreaks = """<table>
|
||||
<tr>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Jill</td>
|
||||
<td>Smith
|
||||
Jackson</td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson
|
||||
Smith</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
|
||||
table_with_header_column = """<table>
|
||||
<tr>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Jill</th>
|
||||
<td>Smith</td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Eve</th>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
|
||||
table_head_body = """<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Jill</td>
|
||||
<td>Smith</td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>"""
|
||||
|
||||
table_head_body_missing_head = """<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<td>Firstname</td>
|
||||
<td>Lastname</td>
|
||||
<td>Age</td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Jill</td>
|
||||
<td>Smith</td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>"""
|
||||
|
||||
table_missing_text = """<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th>Lastname</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Jill</td>
|
||||
<td></td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>"""
|
||||
|
||||
table_missing_head = """<table>
|
||||
<tr>
|
||||
<td>Firstname</td>
|
||||
<td>Lastname</td>
|
||||
<td>Age</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Jill</td>
|
||||
<td>Smith</td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
table_body = """<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Firstname</td>
|
||||
<td>Lastname</td>
|
||||
<td>Age</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Jill</td>
|
||||
<td>Smith</td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>"""
|
||||
|
||||
table_with_caption = """TEXT<table><caption>Caption</caption>
|
||||
<tbody><tr><td>Firstname</td>
|
||||
<td>Lastname</td>
|
||||
<td>Age</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>"""
|
||||
|
||||
table_with_colspan = """<table>
|
||||
<tr>
|
||||
<th colspan="2">Name</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="1">Jill</td>
|
||||
<td>Smith</td>
|
||||
<td>50</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Eve</td>
|
||||
<td>Jackson</td>
|
||||
<td>94</td>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
table_with_undefined_colspan = """<table>
|
||||
<tr>
|
||||
<th colspan="undefined">Name</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="-1">Jill</td>
|
||||
<td>Smith</td>
|
||||
</tr>
|
||||
</table>"""
|
||||
|
||||
|
||||
def test_table():
|
||||
assert md(table) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_with_html_content) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| **Jill** | *Smith* | [50](#) |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_with_paragraphs) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_with_linebreaks) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith Jackson | 50 |\n| Eve | Jackson Smith | 94 |\n\n'
|
||||
assert md(table_with_header_column) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_head_body) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_head_body_missing_head) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_missing_text) == '\n\n| | Lastname | Age |\n| --- | --- | --- |\n| Jill | | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_missing_head) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_body) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_with_caption) == 'TEXT\n\nCaption\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n\n'
|
||||
assert md(table_with_colspan) == '\n\n| Name | | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_with_undefined_colspan) == '\n\n| Name | Age |\n| --- | --- |\n| Jill | Smith |\n\n'
|
||||
Reference in New Issue
Block a user