Compare commits
159 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be3a7f4672 | ||
|
|
3b4a014f25 | ||
|
|
57d4f37923 | ||
|
|
d5fb0fbb85 | ||
|
|
e4df41225d | ||
|
|
804a3f8f07 | ||
|
|
7d0bf46057 | ||
|
|
2f9a42d3b8 | ||
|
|
96a25cfbf3 | ||
|
|
0477a0c8a0 | ||
|
|
f33ccd7c1a | ||
|
|
a2f82678f7 | ||
|
|
60967c1c95 | ||
|
|
c7718b6d81 | ||
|
|
2b22d239ad | ||
|
|
8219d2a673 | ||
|
|
e6e23fd512 | ||
|
|
433fad2dec | ||
|
|
4fb451ffa6 | ||
|
|
0c8ac578c9 | ||
|
|
e8d041c251 | ||
|
|
f729c3ba43 | ||
|
|
eddfdae4ca | ||
|
|
8f047753ae | ||
|
|
50b3b73a8f | ||
|
|
0310216877 | ||
|
|
194c646a20 | ||
|
|
9914474828 | ||
|
|
6263f0e5f0 | ||
|
|
17d8586843 | ||
|
|
59eb069700 | ||
|
|
e79971a7eb | ||
|
|
2c533339cf | ||
|
|
5adda130b8 | ||
|
|
5f1b98e25d | ||
|
|
16acd2b763 | ||
|
|
2b8cf444f1 | ||
|
|
207d0f4ec6 | ||
|
|
ebb9ea713d | ||
|
|
d375116807 | ||
|
|
87b9f6c88e | ||
|
|
bda367dad9 | ||
|
|
61e8940486 | ||
|
|
35479d2d3b | ||
|
|
b589863715 | ||
|
|
423b7e948c | ||
|
|
0ea95de4d0 | ||
|
|
ed3eee78d2 | ||
|
|
eb0330bfc6 | ||
|
|
ddda696396 | ||
|
|
0a1343a538 | ||
|
|
9d0b839b73 | ||
|
|
28793ac0b3 | ||
|
|
d3eff11617 | ||
|
|
bd6b581122 | ||
|
|
9231704988 | ||
|
|
c8f7cf63e3 | ||
|
|
12a68a7d14 | ||
|
|
1613c302bc | ||
|
|
478b1c7e13 | ||
|
|
ffcf6cbcb2 | ||
|
|
0ab0452414 | ||
|
|
b62b067cbd | ||
|
|
cb2646cd93 | ||
|
|
9692b5e714 | ||
|
|
ac68c53a7d | ||
|
|
55c9e84f38 | ||
|
|
40dd30419c | ||
|
|
da56f7f56a | ||
|
|
8400b39dd9 | ||
|
|
5fc1441fe7 | ||
|
|
044615eff1 | ||
|
|
99875683ac | ||
|
|
dbd9f3f3d2 | ||
|
|
0fdeb1ff6e | ||
|
|
eaeb0603eb | ||
|
|
6a2f3a4b42 | ||
|
|
cb73590623 | ||
|
|
22180a166d | ||
|
|
16d8a0e1f7 | ||
|
|
4aa6cf2a24 | ||
|
|
828e116530 | ||
|
|
62e9f0de02 | ||
|
|
59417ab115 | ||
|
|
cec570fc49 | ||
|
|
a6a31624ad | ||
|
|
6f3732307d | ||
|
|
8f6d7e500d | ||
|
|
917b01e548 | ||
|
|
e96351b666 | ||
|
|
129c4ef060 | ||
|
|
652714859d | ||
|
|
9cb940cbc0 | ||
|
|
70ef9b6e48 | ||
|
|
91d53ddd5a | ||
|
|
079f32f6cd | ||
|
|
89b577e91e | ||
|
|
4bf2ea44fc | ||
|
|
77797ebb79 | ||
|
|
ea5b22824b | ||
|
|
9f3c4c9fa0 | ||
|
|
967db26b3a | ||
|
|
ea81407b87 | ||
|
|
e6da15c173 | ||
|
|
7dac92e85e | ||
|
|
ec5858e42f | ||
|
|
fc29483899 | ||
|
|
bd7a8d6990 | ||
|
|
ddfbf6a364 | ||
|
|
91a64e3cd4 | ||
|
|
02bb914ef3 | ||
|
|
0fee4b0a80 | ||
|
|
10e1ff3e6e | ||
|
|
73800ced36 | ||
|
|
1538cacb94 | ||
|
|
21c0d034d0 | ||
|
|
f59f9f9a54 | ||
|
|
bd22a16c9e | ||
|
|
55fb96e3c0 | ||
|
|
5f102d5223 | ||
|
|
e3ddc789a2 | ||
|
|
651d5f00e8 | ||
|
|
3cf324d03d | ||
|
|
96f7e7d307 | ||
|
|
e1dbbfad42 | ||
|
|
2d0cd97323 | ||
|
|
d4882b86b9 | ||
|
|
b47d5f11c8 | ||
|
|
29c794e17d | ||
|
|
e877602a5e | ||
|
|
5580b0b51d | ||
|
|
650f377b64 | ||
|
|
7ee87b1d32 | ||
|
|
16dbc471b9 | ||
|
|
c04ec855dd | ||
|
|
8da0bdf998 | ||
|
|
ec185e2e9c | ||
|
|
a59e4b9f48 | ||
|
|
fd293a9714 | ||
|
|
99365de669 | ||
|
|
a79ed44ec3 | ||
|
|
29a4e551f7 | ||
|
|
b3ac4606a6 | ||
|
|
f093843f40 | ||
|
|
de6f91af0e | ||
|
|
8c28ade348 | ||
|
|
a152c5b706 | ||
|
|
292d64bbf4 | ||
|
|
db96eeb785 | ||
|
|
73f7644c0d | ||
|
|
7685738344 | ||
|
|
92a73c8dfe | ||
|
|
3354f143d8 | ||
|
|
2c7e4a0100 | ||
|
|
4f00d638d2 | ||
|
|
d23596706d | ||
|
|
6a0e5d8176 | ||
|
|
7b788bafd4 | ||
|
|
146104b41f |
14
.github/workflows/python-app.yml
vendored
14
.github/workflows/python-app.yml
vendored
@@ -16,18 +16,14 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- name: Set up Python 3.6
|
- name: Set up Python 3.8
|
||||||
uses: actions/setup-python@v2
|
uses: actions/setup-python@v2
|
||||||
with:
|
with:
|
||||||
python-version: 3.6
|
python-version: 3.8
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip
|
python -m pip install --upgrade pip
|
||||||
pip install flake8==2.5.4 pytest
|
pip install tox
|
||||||
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
|
- name: Lint and test
|
||||||
- name: Lint with flake8
|
|
||||||
run: |
|
run: |
|
||||||
python setup.py lint
|
tox
|
||||||
- name: Test with pytest
|
|
||||||
run: |
|
|
||||||
python setup.py test
|
|
||||||
|
|||||||
2
.github/workflows/python-publish.yml
vendored
2
.github/workflows/python-publish.yml
vendored
@@ -17,7 +17,7 @@ jobs:
|
|||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v2
|
uses: actions/setup-python@v2
|
||||||
with:
|
with:
|
||||||
python-version: '3.x'
|
python-version: '3.8'
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip
|
python -m pip install --upgrade pip
|
||||||
|
|||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -8,3 +8,5 @@
|
|||||||
/MANIFEST
|
/MANIFEST
|
||||||
/venv
|
/venv
|
||||||
build/
|
build/
|
||||||
|
.vscode/settings.json
|
||||||
|
.tox/
|
||||||
|
|||||||
142
README.rst
142
README.rst
@@ -32,14 +32,14 @@ Convert some HTML to Markdown:
|
|||||||
from markdownify import markdownify as md
|
from markdownify import markdownify as md
|
||||||
md('<b>Yay</b> <a href="http://github.com">GitHub</a>') # > '**Yay** [GitHub](http://github.com)'
|
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
|
.. code:: python
|
||||||
|
|
||||||
from markdownify import markdownify as md
|
from markdownify import markdownify as md
|
||||||
md('<b>Yay</b> <a href="http://github.com">GitHub</a>', strip=['a']) # > '**Yay** GitHub'
|
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
|
.. code:: python
|
||||||
|
|
||||||
@@ -53,16 +53,20 @@ Options
|
|||||||
Markdownify supports the following options:
|
Markdownify supports the following options:
|
||||||
|
|
||||||
strip
|
strip
|
||||||
A list of tags to strip (blacklist). This option can't be used with the
|
A list of tags to strip. This option can't be used with the
|
||||||
``convert`` option.
|
``convert`` option.
|
||||||
|
|
||||||
convert
|
convert
|
||||||
A list of tags to convert (whitelist). This option can't be used with the
|
A list of tags to convert. This option can't be used with the
|
||||||
``strip`` option.
|
``strip`` option.
|
||||||
|
|
||||||
autolinks
|
autolinks
|
||||||
A boolean indicating whether the "automatic link" style should be used when
|
A boolean indicating whether the "automatic link" style should be used when
|
||||||
a ``a`` tag's contents match its href. Defaults to ``True``
|
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
|
heading_style
|
||||||
Defines how headings should be converted. Accepted values are ``ATX``,
|
Defines how headings should be converted. Accepted values are ``ATX``,
|
||||||
@@ -75,17 +79,131 @@ bullets
|
|||||||
lists are nested. Otherwise, the bullet will alternate based on nesting
|
lists are nested. Otherwise, the bullet will alternate based on nesting
|
||||||
level. Defaults to ``'*+-'``.
|
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^``.
|
||||||
|
|
||||||
|
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``.
|
||||||
|
|
||||||
|
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
|
Options may be specified as kwargs to the ``markdownify`` function, or as a
|
||||||
nested ``Options`` class in ``MarkdownConverter`` subclasses.
|
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
|
Development
|
||||||
===========
|
===========
|
||||||
|
|
||||||
To run tests:
|
To run tests and the linter run ``pip install tox`` once, then ``tox``.
|
||||||
|
|
||||||
``python setup.py test``
|
|
||||||
|
|
||||||
To lint:
|
|
||||||
|
|
||||||
``python setup.py lint``
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
from bs4 import BeautifulSoup, NavigableString, Comment
|
from bs4 import BeautifulSoup, NavigableString, Comment, Doctype
|
||||||
|
from textwrap import fill
|
||||||
import re
|
import re
|
||||||
import six
|
import six
|
||||||
|
|
||||||
@@ -6,6 +7,7 @@ import six
|
|||||||
convert_heading_re = re.compile(r'convert_h(\d+)')
|
convert_heading_re = re.compile(r'convert_h(\d+)')
|
||||||
line_beginning_re = re.compile(r'^', re.MULTILINE)
|
line_beginning_re = re.compile(r'^', re.MULTILINE)
|
||||||
whitespace_re = re.compile(r'[\t ]+')
|
whitespace_re = re.compile(r'[\t ]+')
|
||||||
|
all_whitespace_re = re.compile(r'[\s]+')
|
||||||
html_heading_re = re.compile(r'h[1-6]')
|
html_heading_re = re.compile(r'h[1-6]')
|
||||||
|
|
||||||
|
|
||||||
@@ -15,11 +17,13 @@ ATX_CLOSED = 'atx_closed'
|
|||||||
UNDERLINED = 'underlined'
|
UNDERLINED = 'underlined'
|
||||||
SETEXT = UNDERLINED
|
SETEXT = UNDERLINED
|
||||||
|
|
||||||
|
# Newline style
|
||||||
|
SPACES = 'spaces'
|
||||||
|
BACKSLASH = 'backslash'
|
||||||
|
|
||||||
def escape(text):
|
# Strong and emphasis style
|
||||||
if not text:
|
ASTERISK = '*'
|
||||||
return ''
|
UNDERSCORE = '_'
|
||||||
return text.replace('_', r'\_')
|
|
||||||
|
|
||||||
|
|
||||||
def chomp(text):
|
def chomp(text):
|
||||||
@@ -35,17 +39,45 @@ def chomp(text):
|
|||||||
return (prefix, suffix, text)
|
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. markup_fn is necessary to allow for
|
||||||
|
references to self.strong_em_symbol etc.
|
||||||
|
"""
|
||||||
|
def implementation(self, el, text, convert_as_inline):
|
||||||
|
markup = markup_fn(self)
|
||||||
|
prefix, suffix, text = chomp(text)
|
||||||
|
if not text:
|
||||||
|
return ''
|
||||||
|
return '%s%s%s%s%s' % (prefix, markup, text, markup, suffix)
|
||||||
|
return implementation
|
||||||
|
|
||||||
|
|
||||||
def _todict(obj):
|
def _todict(obj):
|
||||||
return dict((k, getattr(obj, k)) for k in dir(obj) if not k.startswith('_'))
|
return dict((k, getattr(obj, k)) for k in dir(obj) if not k.startswith('_'))
|
||||||
|
|
||||||
|
|
||||||
class MarkdownConverter(object):
|
class MarkdownConverter(object):
|
||||||
class DefaultOptions:
|
class DefaultOptions:
|
||||||
strip = None
|
|
||||||
convert = None
|
|
||||||
autolinks = True
|
autolinks = True
|
||||||
heading_style = UNDERLINED
|
|
||||||
bullets = '*+-' # An iterable of bullet types.
|
bullets = '*+-' # An iterable of bullet types.
|
||||||
|
code_language = ''
|
||||||
|
code_language_callback = None
|
||||||
|
convert = None
|
||||||
|
default_title = False
|
||||||
|
escape_asterisks = True
|
||||||
|
escape_underscores = 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):
|
class Options(DefaultOptions):
|
||||||
pass
|
pass
|
||||||
@@ -62,23 +94,51 @@ class MarkdownConverter(object):
|
|||||||
|
|
||||||
def convert(self, html):
|
def convert(self, html):
|
||||||
soup = BeautifulSoup(html, 'html.parser')
|
soup = BeautifulSoup(html, 'html.parser')
|
||||||
|
return self.convert_soup(soup)
|
||||||
|
|
||||||
|
def convert_soup(self, soup):
|
||||||
return self.process_tag(soup, convert_as_inline=False, children_only=True)
|
return self.process_tag(soup, convert_as_inline=False, children_only=True)
|
||||||
|
|
||||||
def process_tag(self, node, convert_as_inline, children_only=False):
|
def process_tag(self, node, convert_as_inline, children_only=False):
|
||||||
text = ''
|
text = ''
|
||||||
# markdown headings can't include block elements (elements w/newlines)
|
|
||||||
|
# markdown headings or cells can't include
|
||||||
|
# block elements (elements w/newlines)
|
||||||
isHeading = html_heading_re.match(node.name) is not None
|
isHeading = html_heading_re.match(node.name) is not None
|
||||||
|
isCell = node.name in ['td', 'th']
|
||||||
convert_children_as_inline = convert_as_inline
|
convert_children_as_inline = convert_as_inline
|
||||||
|
|
||||||
if not children_only and isHeading:
|
if not children_only and (isHeading or isCell):
|
||||||
convert_children_as_inline = True
|
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
|
# Convert the children first
|
||||||
for el in node.children:
|
for el in node.children:
|
||||||
if isinstance(el, Comment):
|
if isinstance(el, Comment) or isinstance(el, Doctype):
|
||||||
continue
|
continue
|
||||||
elif isinstance(el, NavigableString):
|
elif isinstance(el, NavigableString):
|
||||||
text += self.process_text(six.text_type(el))
|
text += self.process_text(el)
|
||||||
else:
|
else:
|
||||||
text += self.process_tag(el, convert_children_as_inline)
|
text += self.process_tag(el, convert_children_as_inline)
|
||||||
|
|
||||||
@@ -89,8 +149,26 @@ class MarkdownConverter(object):
|
|||||||
|
|
||||||
return text
|
return text
|
||||||
|
|
||||||
def process_text(self, text):
|
def process_text(self, el):
|
||||||
return escape(whitespace_re.sub(' ', text or ''))
|
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):
|
def __getattr__(self, attr):
|
||||||
# Handle headings
|
# Handle headings
|
||||||
@@ -118,6 +196,15 @@ class MarkdownConverter(object):
|
|||||||
else:
|
else:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
def escape(self, text):
|
||||||
|
if not text:
|
||||||
|
return ''
|
||||||
|
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):
|
def indent(self, text, level):
|
||||||
return line_beginning_re.sub('\t' * level, text) if text else ''
|
return line_beginning_re.sub('\t' * level, text) if text else ''
|
||||||
|
|
||||||
@@ -129,45 +216,56 @@ class MarkdownConverter(object):
|
|||||||
prefix, suffix, text = chomp(text)
|
prefix, suffix, text = chomp(text)
|
||||||
if not text:
|
if not text:
|
||||||
return ''
|
return ''
|
||||||
if convert_as_inline:
|
|
||||||
return text
|
|
||||||
href = el.get('href')
|
href = el.get('href')
|
||||||
title = el.get('title')
|
title = el.get('title')
|
||||||
# For the replacement see #29: text nodes underscores are escaped
|
# For the replacement see #29: text nodes underscores are escaped
|
||||||
if self.options['autolinks'] and text.replace(r'\_', '_') == href and not title:
|
if (self.options['autolinks']
|
||||||
|
and text.replace(r'\_', '_') == href
|
||||||
|
and not title
|
||||||
|
and not self.options['default_title']):
|
||||||
# Shortcut syntax
|
# Shortcut syntax
|
||||||
return '<%s>' % href
|
return '<%s>' % href
|
||||||
|
if self.options['default_title'] and not title:
|
||||||
|
title = href
|
||||||
title_part = ' "%s"' % title.replace('"', r'\"') if title else ''
|
title_part = ' "%s"' % title.replace('"', r'\"') if title else ''
|
||||||
return '%s[%s](%s%s)%s' % (prefix, text, href, title_part, suffix) if href else text
|
return '%s[%s](%s%s)%s' % (prefix, text, href, title_part, suffix) if href else text
|
||||||
|
|
||||||
def convert_b(self, el, text, convert_as_inline):
|
convert_b = abstract_inline_conversion(lambda self: 2 * self.options['strong_em_symbol'])
|
||||||
return self.convert_strong(el, text, convert_as_inline)
|
|
||||||
|
|
||||||
def convert_blockquote(self, el, text, convert_as_inline):
|
def convert_blockquote(self, el, text, convert_as_inline):
|
||||||
|
|
||||||
if convert_as_inline:
|
if convert_as_inline:
|
||||||
return text
|
return text
|
||||||
|
|
||||||
return '\n' + (line_beginning_re.sub('> ', text) + '\n\n') if text else ''
|
return '\n' + (line_beginning_re.sub('> ', text.strip()) + '\n\n') if text else ''
|
||||||
|
|
||||||
def convert_br(self, el, text, convert_as_inline):
|
def convert_br(self, el, text, convert_as_inline):
|
||||||
if convert_as_inline:
|
if convert_as_inline:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
return ' \n'
|
if self.options['newline_style'].lower() == BACKSLASH:
|
||||||
|
return '\\\n'
|
||||||
|
else:
|
||||||
|
return ' \n'
|
||||||
|
|
||||||
def convert_em(self, el, text, convert_as_inline):
|
def convert_code(self, el, text, convert_as_inline):
|
||||||
prefix, suffix, text = chomp(text)
|
if el.parent.name == 'pre':
|
||||||
if not text:
|
return text
|
||||||
return ''
|
converter = abstract_inline_conversion(lambda self: '`')
|
||||||
return '%s*%s*%s' % (prefix, text, suffix)
|
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):
|
def convert_hn(self, n, el, text, convert_as_inline):
|
||||||
if convert_as_inline:
|
if convert_as_inline:
|
||||||
return text
|
return text
|
||||||
|
|
||||||
style = self.options['heading_style']
|
style = self.options['heading_style'].lower()
|
||||||
text = text.rstrip()
|
text = text.strip()
|
||||||
if style == UNDERLINED and n <= 2:
|
if style == UNDERLINED and n <= 2:
|
||||||
line = '=' if n == 1 else '-'
|
line = '=' if n == 1 else '-'
|
||||||
return self.underline(text, line)
|
return self.underline(text, line)
|
||||||
@@ -176,8 +274,21 @@ class MarkdownConverter(object):
|
|||||||
return '%s %s %s\n\n' % (hashes, text, hashes)
|
return '%s %s %s\n\n' % (hashes, text, hashes)
|
||||||
return '%s %s\n\n' % (hashes, text)
|
return '%s %s\n\n' % (hashes, text)
|
||||||
|
|
||||||
def convert_i(self, el, text, convert_as_inline):
|
def convert_hr(self, el, text, convert_as_inline):
|
||||||
return self.convert_em(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):
|
def convert_list(self, el, text, convert_as_inline):
|
||||||
|
|
||||||
@@ -185,6 +296,9 @@ class MarkdownConverter(object):
|
|||||||
# Ignoring convert_to_inline for list.
|
# Ignoring convert_to_inline for list.
|
||||||
|
|
||||||
nested = False
|
nested = False
|
||||||
|
before_paragraph = False
|
||||||
|
if el.next_sibling and el.next_sibling.name not in ['ul', 'ol']:
|
||||||
|
before_paragraph = True
|
||||||
while el:
|
while el:
|
||||||
if el.name == 'li':
|
if el.name == 'li':
|
||||||
nested = True
|
nested = True
|
||||||
@@ -193,7 +307,7 @@ class MarkdownConverter(object):
|
|||||||
if nested:
|
if nested:
|
||||||
# remove trailing newline if nested
|
# remove trailing newline if nested
|
||||||
return '\n' + self.indent(text, 1).rstrip()
|
return '\n' + self.indent(text, 1).rstrip()
|
||||||
return '\n' + text + '\n'
|
return text + ('\n' if before_paragraph else '')
|
||||||
|
|
||||||
convert_ul = convert_list
|
convert_ul = convert_list
|
||||||
convert_ol = convert_list
|
convert_ol = convert_list
|
||||||
@@ -214,28 +328,94 @@ class MarkdownConverter(object):
|
|||||||
el = el.parent
|
el = el.parent
|
||||||
bullets = self.options['bullets']
|
bullets = self.options['bullets']
|
||||||
bullet = bullets[depth % len(bullets)]
|
bullet = bullets[depth % len(bullets)]
|
||||||
return '%s %s\n' % (bullet, text or '')
|
return '%s %s\n' % (bullet, (text or '').strip())
|
||||||
|
|
||||||
def convert_p(self, el, text, convert_as_inline):
|
def convert_p(self, el, text, convert_as_inline):
|
||||||
if convert_as_inline:
|
if convert_as_inline:
|
||||||
return text
|
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 ''
|
return '%s\n\n' % text if text else ''
|
||||||
|
|
||||||
def convert_strong(self, el, text, convert_as_inline):
|
def convert_pre(self, el, text, convert_as_inline):
|
||||||
prefix, suffix, text = chomp(text)
|
|
||||||
if not text:
|
if not text:
|
||||||
return ''
|
return ''
|
||||||
return '%s**%s**%s' % (prefix, text, suffix)
|
code_language = self.options['code_language']
|
||||||
|
|
||||||
def convert_img(self, el, text, convert_as_inline):
|
if self.options['code_language_callback']:
|
||||||
alt = el.attrs.get('alt', None) or ''
|
code_language = self.options['code_language_callback'](el) or code_language
|
||||||
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:
|
|
||||||
return alt
|
|
||||||
|
|
||||||
return '' % (alt, src, title_part)
|
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:
|
||||||
|
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:
|
||||||
|
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:
|
||||||
|
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, **options):
|
def markdownify(html, **options):
|
||||||
|
|||||||
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()
|
||||||
68
setup.py
68
setup.py
@@ -2,7 +2,6 @@
|
|||||||
import codecs
|
import codecs
|
||||||
import os
|
import os
|
||||||
from setuptools import setup, find_packages
|
from setuptools import setup, find_packages
|
||||||
from setuptools.command.test import test as TestCommand, Command
|
|
||||||
|
|
||||||
|
|
||||||
read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read()
|
read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read()
|
||||||
@@ -10,52 +9,10 @@ read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read()
|
|||||||
pkgmeta = {
|
pkgmeta = {
|
||||||
'__title__': 'markdownify',
|
'__title__': 'markdownify',
|
||||||
'__author__': 'Matthew Tretter',
|
'__author__': 'Matthew Tretter',
|
||||||
'__version__': '0.6.4',
|
'__version__': '0.11.6',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read()
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
class LintCommand(Command):
|
|
||||||
"""
|
|
||||||
A copy of flake8's Flake8Command
|
|
||||||
|
|
||||||
"""
|
|
||||||
description = "Run flake8 on modules registered in setuptools"
|
|
||||||
user_options = []
|
|
||||||
|
|
||||||
def initialize_options(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def finalize_options(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def distribution_files(self):
|
|
||||||
if self.distribution.packages:
|
|
||||||
for package in self.distribution.packages:
|
|
||||||
yield package.replace(".", os.path.sep)
|
|
||||||
|
|
||||||
if self.distribution.py_modules:
|
|
||||||
for filename in self.distribution.py_modules:
|
|
||||||
yield "%s.py" % filename
|
|
||||||
|
|
||||||
def run(self):
|
|
||||||
from flake8.engine import get_style_guide
|
|
||||||
flake8_style = get_style_guide(config_file='setup.cfg')
|
|
||||||
paths = self.distribution_files()
|
|
||||||
report = flake8_style.check_files(paths)
|
|
||||||
raise SystemExit(report.total_errors > 0)
|
|
||||||
|
|
||||||
|
|
||||||
setup(
|
setup(
|
||||||
name='markdownify',
|
name='markdownify',
|
||||||
@@ -69,14 +26,9 @@ setup(
|
|||||||
packages=find_packages(),
|
packages=find_packages(),
|
||||||
zip_safe=False,
|
zip_safe=False,
|
||||||
include_package_data=True,
|
include_package_data=True,
|
||||||
setup_requires=[
|
|
||||||
'flake8',
|
|
||||||
],
|
|
||||||
tests_require=[
|
|
||||||
'pytest',
|
|
||||||
],
|
|
||||||
install_requires=[
|
install_requires=[
|
||||||
'beautifulsoup4', 'six'
|
'beautifulsoup4>=4.9,<5',
|
||||||
|
'six>=1.15,<2',
|
||||||
],
|
],
|
||||||
classifiers=[
|
classifiers=[
|
||||||
'Environment :: Web Environment',
|
'Environment :: Web Environment',
|
||||||
@@ -87,10 +39,14 @@ setup(
|
|||||||
'Programming Language :: Python :: 2.5',
|
'Programming Language :: Python :: 2.5',
|
||||||
'Programming Language :: Python :: 2.6',
|
'Programming Language :: Python :: 2.6',
|
||||||
'Programming Language :: Python :: 2.7',
|
'Programming Language :: Python :: 2.7',
|
||||||
|
'Programming Language :: Python :: 3.6',
|
||||||
|
'Programming Language :: Python :: 3.7',
|
||||||
|
'Programming Language :: Python :: 3.8',
|
||||||
'Topic :: Utilities'
|
'Topic :: Utilities'
|
||||||
],
|
],
|
||||||
cmdclass={
|
entry_points={
|
||||||
'test': PyTest,
|
'console_scripts': [
|
||||||
'lint': LintCommand,
|
'markdownify = markdownify.main:main'
|
||||||
},
|
]
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|||||||
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,17 @@
|
|||||||
from markdownify import markdownify as md
|
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():
|
def test_nested():
|
||||||
text = md('<p>This is an <a href="http://example.com/">example link</a>.</p>')
|
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'
|
assert text == 'This is an [example link](http://example.com/).\n\n'
|
||||||
@@ -14,3 +25,15 @@ def test_ignore_comments():
|
|||||||
def test_ignore_comments_with_other_tags():
|
def test_ignore_comments_with_other_tags():
|
||||||
text = md("<!-- This is a comment --><a href='http://example.com/'>example link</a>")
|
text = md("<!-- This is a comment --><a href='http://example.com/'>example link</a>")
|
||||||
assert text == "[example link](http://example.com/)"
|
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'
|
||||||
|
|||||||
@@ -1,41 +1,17 @@
|
|||||||
from markdownify import markdownify as md, ATX, ATX_CLOSED
|
from markdownify import markdownify as md, ATX, ATX_CLOSED, BACKSLASH, UNDERSCORE
|
||||||
import re
|
|
||||||
|
|
||||||
|
|
||||||
nested_uls = re.sub(r'\s+', '', """
|
def inline_tests(tag, markup):
|
||||||
<ul>
|
# test template for different inline tags
|
||||||
<li>1
|
assert md(f'<{tag}>Hello</{tag}>') == f'{markup}Hello{markup}'
|
||||||
<ul>
|
assert md(f'foo <{tag}>Hello</{tag}> bar') == f'foo {markup}Hello{markup} bar'
|
||||||
<li>a
|
assert md(f'foo<{tag}> Hello</{tag}> bar') == f'foo {markup}Hello{markup} bar'
|
||||||
<ul>
|
assert md(f'foo <{tag}>Hello </{tag}>bar') == f'foo {markup}Hello{markup} bar'
|
||||||
<li>I</li>
|
assert md(f'foo <{tag}></{tag}> bar') in ['foo bar', 'foo bar'] # Either is OK
|
||||||
<li>II</li>
|
|
||||||
<li>III</li>
|
|
||||||
</ul>
|
|
||||||
</li>
|
|
||||||
<li>b</li>
|
|
||||||
<li>c</li>
|
|
||||||
</ul>
|
|
||||||
</li>
|
|
||||||
<li>2</li>
|
|
||||||
<li>3</li>
|
|
||||||
</ul>""")
|
|
||||||
|
|
||||||
|
|
||||||
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_a():
|
def test_a():
|
||||||
assert md('<a href="https://google.com">Google</a>') == '[Google](https://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>', autolinks=False) == '[https://google.com](https://google.com)'
|
|
||||||
assert md('<a href="https://google.com">https://google.com</a>') == '<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>') == '<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)'
|
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)'
|
||||||
@@ -51,6 +27,7 @@ def test_a_spaces():
|
|||||||
def test_a_with_title():
|
def test_a_with_title():
|
||||||
text = md('<a href="http://google.com" title="The "Goog"">Google</a>')
|
text = md('<a href="http://google.com" title="The "Goog"">Google</a>')
|
||||||
assert text == r'[Google](http://google.com "The \"Goog\"")'
|
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():
|
def test_a_shortcut():
|
||||||
@@ -59,8 +36,7 @@ def test_a_shortcut():
|
|||||||
|
|
||||||
|
|
||||||
def test_a_no_autolinks():
|
def test_a_no_autolinks():
|
||||||
text = md('<a href="http://google.com">http://google.com</a>', autolinks=False)
|
assert md('<a href="https://google.com">https://google.com</a>', autolinks=False) == '[https://google.com](https://google.com)'
|
||||||
assert text == '[http://google.com](http://google.com)'
|
|
||||||
|
|
||||||
|
|
||||||
def test_b():
|
def test_b():
|
||||||
@@ -76,30 +52,61 @@ def test_b_spaces():
|
|||||||
|
|
||||||
def test_blockquote():
|
def test_blockquote():
|
||||||
assert md('<blockquote>Hello</blockquote>') == '\n> Hello\n\n'
|
assert md('<blockquote>Hello</blockquote>') == '\n> Hello\n\n'
|
||||||
|
assert md('<blockquote>\nHello\n</blockquote>') == '\n> Hello\n\n'
|
||||||
|
|
||||||
|
|
||||||
|
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():
|
def test_blockquote_with_paragraph():
|
||||||
assert md('<blockquote>Hello</blockquote><p>handsome</p>') == '\n> Hello\n\nhandsome\n\n'
|
assert md('<blockquote>Hello</blockquote><p>handsome</p>') == '\n> Hello\n\nhandsome\n\n'
|
||||||
|
|
||||||
|
|
||||||
def test_nested_blockquote():
|
def test_blockquote_nested():
|
||||||
text = md('<blockquote>And she was like <blockquote>Hello</blockquote></blockquote>')
|
text = md('<blockquote>And she was like <blockquote>Hello</blockquote></blockquote>')
|
||||||
assert text == '\n> And she was like \n> > Hello\n> \n> \n\n'
|
assert text == '\n> And she was like \n> > Hello\n\n'
|
||||||
|
|
||||||
|
|
||||||
def test_br():
|
def test_br():
|
||||||
assert md('a<br />b<br />c') == 'a \nb \nc'
|
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`'
|
||||||
|
|
||||||
|
|
||||||
|
def test_del():
|
||||||
|
inline_tests('del', '~~')
|
||||||
|
|
||||||
|
|
||||||
|
def test_div():
|
||||||
|
assert md('Hello</div> World') == 'Hello World'
|
||||||
|
|
||||||
|
|
||||||
def test_em():
|
def test_em():
|
||||||
assert md('<em>Hello</em>') == '*Hello*'
|
inline_tests('em', '*')
|
||||||
|
|
||||||
|
|
||||||
def test_em_spaces():
|
def test_header_with_space():
|
||||||
assert md('foo <em>Hello</em> bar') == 'foo *Hello* bar'
|
assert md('<h3>\n\nHello</h3>') == '### Hello\n\n'
|
||||||
assert md('foo<em> Hello</em> bar') == 'foo *Hello* bar'
|
assert md('<h4>\n\nHello</h4>') == '#### Hello\n\n'
|
||||||
assert md('foo <em>Hello </em>bar') == 'foo *Hello* bar'
|
assert md('<h5>\n\nHello</h5>') == '##### Hello\n\n'
|
||||||
assert md('foo <em></em> bar') == 'foo bar'
|
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():
|
def test_h1():
|
||||||
@@ -112,6 +119,8 @@ def test_h2():
|
|||||||
|
|
||||||
def test_hn():
|
def test_hn():
|
||||||
assert md('<h3>Hello</h3>') == '### Hello\n\n'
|
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'
|
assert md('<h6>Hello</h6>') == '###### Hello\n\n'
|
||||||
|
|
||||||
|
|
||||||
@@ -147,76 +156,113 @@ def test_hn_nested_simple_tag():
|
|||||||
|
|
||||||
|
|
||||||
def test_hn_nested_img():
|
def test_hn_nested_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" />') == ''
|
|
||||||
image_attributes_to_markdown = [
|
image_attributes_to_markdown = [
|
||||||
("", ""),
|
("", "", ""),
|
||||||
("alt='Alt Text'", "Alt Text"),
|
("alt='Alt Text'", "Alt Text", ""),
|
||||||
("alt='Alt Text' title='Optional title'", "Alt Text"),
|
("alt='Alt Text' title='Optional title'", "Alt Text", " \"Optional title\""),
|
||||||
]
|
]
|
||||||
for image_attributes, markdown in image_attributes_to_markdown:
|
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>') == '### 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_hr():
|
def test_hn_atx_headings():
|
||||||
assert md('<hr>hr</hr>') == 'hr'
|
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():
|
def test_head():
|
||||||
assert md('<head>head</head>') == 'head'
|
assert md('<head>head</head>') == 'head'
|
||||||
|
|
||||||
|
|
||||||
def test_atx_headings():
|
def test_hr():
|
||||||
assert md('<h1>Hello</h1>', heading_style=ATX) == '# Hello\n\n'
|
assert md('Hello<hr>World') == 'Hello\n\n---\n\nWorld'
|
||||||
assert md('<h2>Hello</h2>', heading_style=ATX) == '## Hello\n\n'
|
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_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_i():
|
def test_i():
|
||||||
assert md('<i>Hello</i>') == '*Hello*'
|
assert md('<i>Hello</i>') == '*Hello*'
|
||||||
|
|
||||||
|
|
||||||
def test_ol():
|
|
||||||
assert md('<ol><li>a</li><li>b</li></ol>') == '\n1. a\n2. b\n\n'
|
|
||||||
assert md('<ol start="3"><li>a</li><li>b</li></ol>') == '\n3. a\n4. b\n\n'
|
|
||||||
|
|
||||||
|
|
||||||
def test_p():
|
|
||||||
assert md('<p>hello</p>') == 'hello\n\n'
|
|
||||||
|
|
||||||
|
|
||||||
def test_strong():
|
|
||||||
assert md('<strong>Hello</strong>') == '**Hello**'
|
|
||||||
|
|
||||||
|
|
||||||
def test_ul():
|
|
||||||
assert md('<ul><li>a</li><li>b</li></ul>') == '\n* a\n* b\n\n'
|
|
||||||
|
|
||||||
|
|
||||||
def test_inline_ul():
|
|
||||||
assert md('<p>foo</p><ul><li>a</li><li>b</li></ul><p>bar</p>') == 'foo\n\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\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\n'
|
|
||||||
|
|
||||||
|
|
||||||
def test_img():
|
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" title="Optional title" />') == ''
|
||||||
assert md('<img src="/path/to/img.jpg" alt="Alt text" />') == ''
|
assert md('<img src="/path/to/img.jpg" alt="Alt text" />') == ''
|
||||||
|
|
||||||
|
|
||||||
def test_div():
|
def test_kbd():
|
||||||
assert md('Hello</div> World') == 'Hello World'
|
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'
|
||||||
|
|
||||||
|
|
||||||
|
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_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~'
|
||||||
|
|
||||||
|
|
||||||
|
def test_sup():
|
||||||
|
assert md('<sup>foo</sup>') == 'foo'
|
||||||
|
assert md('<sup>foo</sup>', sup_symbol='^') == '^foo^'
|
||||||
|
|
||||||
|
|
||||||
|
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,8 +1,14 @@
|
|||||||
from markdownify import markdownify as md
|
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():
|
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():
|
def test_xml_entities():
|
||||||
|
|||||||
81
tests/test_lists.py
Normal file
81
tests/test_lists.py
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
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'
|
||||||
|
|
||||||
|
|
||||||
|
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'
|
||||||
242
tests/test_tables.py
Normal file
242
tests/test_tables.py
Normal file
@@ -0,0 +1,242 @@
|
|||||||
|
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>Jill</td>
|
||||||
|
<td>Smith</td>
|
||||||
|
<td>50</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Eve</td>
|
||||||
|
<td>Jackson</td>
|
||||||
|
<td>94</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'
|
||||||
Reference in New Issue
Block a user