Compare commits
202 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
079d1721aa | ||
|
|
ed406d3206 | ||
|
|
f320cf87ff | ||
|
|
a79ed44ec3 | ||
|
|
29a4e551f7 | ||
|
|
b3ac4606a6 | ||
|
|
f093843f40 | ||
|
|
de6f91af0e | ||
|
|
8c28ade348 | ||
|
|
a152c5b706 | ||
|
|
292d64bbf4 | ||
|
|
db96eeb785 | ||
|
|
73f7644c0d | ||
|
|
a4d134df97 | ||
|
|
457454c713 | ||
|
|
321e9eb5f6 | ||
|
|
bf24df3e2e | ||
|
|
15329588b1 | ||
|
|
77d1e99bd5 | ||
|
|
34ad8485fa | ||
|
|
f0ce934bf8 | ||
|
|
97c78ef55b | ||
|
|
99cd237f27 | ||
|
|
b7e1ab889d | ||
|
|
29e86aec55 | ||
|
|
453b604096 | ||
|
|
2bde8d3e8e | ||
|
|
4f8937810b | ||
|
|
3544322ed2 | ||
|
|
c4d0a14ce5 | ||
|
|
05ea8dc58a | ||
|
|
7780f82c30 | ||
|
|
7685738344 | ||
|
|
92a73c8dfe | ||
|
|
3354f143d8 | ||
|
|
d558617cd7 | ||
|
|
8c9b029756 | ||
|
|
25d68b4265 | ||
|
|
5561106991 | ||
|
|
1b3136ad04 | ||
|
|
2c7e4a0100 | ||
|
|
4f00d638d2 | ||
|
|
987a2a9cae | ||
|
|
a4461161bc | ||
|
|
ae50065872 | ||
|
|
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 | ||
|
|
ece61a5b1f | ||
|
|
f46fb8ebbb | ||
|
|
e521fd402f | ||
|
|
fd6f8db132 | ||
|
|
c2f32b8049 | ||
|
|
b92428466d | ||
|
|
7f75b0bbce |
33
.github/workflows/python-app.yml
vendored
Normal file
33
.github/workflows/python-app.yml
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
# 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 flake8==3.8.4 pytest
|
||||
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
|
||||
- name: Lint with flake8
|
||||
run: |
|
||||
python setup.py lint
|
||||
- name: Test with pytest
|
||||
run: |
|
||||
python setup.py test
|
||||
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 setuptools wheel twine
|
||||
- name: Build and publish
|
||||
env:
|
||||
TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
|
||||
TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
|
||||
run: |
|
||||
python setup.py sdist bdist_wheel
|
||||
twine upload dist/*
|
||||
11
.gitignore
vendored
Normal file
11
.gitignore
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
*.pyc
|
||||
*.egg
|
||||
.eggs/
|
||||
*.egg-info/
|
||||
.DS_Store
|
||||
/.env
|
||||
/dist
|
||||
/MANIFEST
|
||||
/venv
|
||||
build/
|
||||
.vscode/settings.json
|
||||
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
MANIFEST.in
Normal file
1
MANIFEST.in
Normal file
@@ -0,0 +1 @@
|
||||
include README.rst
|
||||
157
README.rst
157
README.rst
@@ -0,0 +1,157 @@
|
||||
|build| |version| |license| |downloads|
|
||||
|
||||
.. |build| image:: https://img.shields.io/github/workflow/status/matthewwithanm/python-markdownify/Python%20application/develop
|
||||
:alt: GitHub Workflow Status
|
||||
:target: https://github.com/matthewwithanm/python-markdownify/actions?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
|
||||
============
|
||||
|
||||
``pip install markdownify``
|
||||
|
||||
|
||||
Usage
|
||||
=====
|
||||
|
||||
Convert some HTML to Markdown:
|
||||
|
||||
.. code:: python
|
||||
|
||||
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:
|
||||
|
||||
.. 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:
|
||||
|
||||
.. 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^``.
|
||||
|
||||
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 an 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.
|
||||
|
||||
escape_underscores
|
||||
If set to ``False``, do not escape ``_`` to ``\_`` in text.
|
||||
Defaults to ``True``.
|
||||
|
||||
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 ImageBlockConverter(**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:
|
||||
|
||||
.. 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)
|
||||
|
||||
|
||||
Development
|
||||
===========
|
||||
|
||||
To run tests:
|
||||
|
||||
``python setup.py test``
|
||||
|
||||
To lint:
|
||||
|
||||
``python setup.py lint``
|
||||
|
||||
@@ -1,56 +1,186 @@
|
||||
from lxml.html.soupparser import fromstring
|
||||
from bs4 import BeautifulSoup, NavigableString, Comment, Doctype
|
||||
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):
|
||||
# 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 escape(text, escape_underscores):
|
||||
if not text:
|
||||
return ''
|
||||
return text.replace('_', r'\_')
|
||||
if escape_underscores:
|
||||
return text.replace('_', r'\_')
|
||||
return text
|
||||
|
||||
|
||||
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. 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):
|
||||
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 = ''
|
||||
convert = None
|
||||
default_title = False
|
||||
escape_underscores = True
|
||||
heading_style = UNDERLINED
|
||||
newline_style = SPACES
|
||||
strip = None
|
||||
strong_em_symbol = ASTERISK
|
||||
sub_symbol = ''
|
||||
sup_symbol = ''
|
||||
|
||||
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 ''
|
||||
|
||||
# dont remove any whitespace when handling pre or code in pre
|
||||
if not (el.parent.name == 'pre'
|
||||
or (el.parent.name == 'code'
|
||||
and el.parent.parent.name == 'pre')):
|
||||
text = whitespace_re.sub(' ', text)
|
||||
|
||||
if el.parent.name != 'code':
|
||||
text = escape(text, self.options['escape_underscores'])
|
||||
|
||||
# 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 +190,183 @@ 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 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) + '\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.rstrip()
|
||||
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:
|
||||
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"):
|
||||
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
|
||||
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 ''
|
||||
return '\n```%s\n%s\n```\n' % (self.options['code_language'], text)
|
||||
|
||||
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_td(self, el, text, convert_as_inline):
|
||||
return ' ' + text + ' |'
|
||||
|
||||
def convert_th(self, el, text, convert_as_inline):
|
||||
return ' ' + text + ' |'
|
||||
|
||||
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])
|
||||
overline = ''
|
||||
underline = ''
|
||||
if is_headrow and not el.previous_sibling:
|
||||
# first row and is headline: print headline underline
|
||||
underline += '| ' + ' | '.join(['---'] * len(cells)) + ' |' + '\n'
|
||||
elif not el.previous_sibling and not el.parent.name != 'table':
|
||||
# first row, not headline, and the parent is sth. like tbody:
|
||||
# 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)
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
__version__ = '0.1.0'
|
||||
@@ -1,5 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
from nose.core import run, collector
|
||||
|
||||
if __name__ == '__main__':
|
||||
run()
|
||||
79
setup.py
79
setup.py
@@ -2,43 +2,98 @@
|
||||
import codecs
|
||||
import os
|
||||
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()
|
||||
execfile(os.path.join(os.path.dirname(__file__), 'markdownify', 'version.py'))
|
||||
|
||||
pkgmeta = {
|
||||
'__title__': 'markdownify',
|
||||
'__author__': 'Matthew Tretter',
|
||||
'__version__': '0.10.3',
|
||||
}
|
||||
|
||||
|
||||
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.api.legacy 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(
|
||||
name='python-markdownify',
|
||||
name='markdownify',
|
||||
description='Convert HTML to markdown.',
|
||||
long_description=read(os.path.join(os.path.dirname(__file__), 'README.rst')),
|
||||
version=__version__,
|
||||
author='Matthew Tretter',
|
||||
author_email='matthew@exanimo.com',
|
||||
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,
|
||||
setup_requires=[
|
||||
'flake8>=3.8,<5',
|
||||
],
|
||||
tests_require=[
|
||||
'nose',
|
||||
'unittest2',
|
||||
'pytest>=6.2,<7',
|
||||
],
|
||||
install_requires=[
|
||||
'lxml',
|
||||
'BeautifulSoup',
|
||||
'beautifulsoup4>=4.9,<5', 'six>=1.15,<2'
|
||||
],
|
||||
classifiers=[
|
||||
'Environment :: Web Environment',
|
||||
'Framework :: Django',
|
||||
'Intended Audience :: Developers',
|
||||
'License :: OSI Approved :: BSD License',
|
||||
'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'
|
||||
],
|
||||
setup_requires=[],
|
||||
test_suite='runtests.collector',
|
||||
cmdclass={
|
||||
'test': PyTest,
|
||||
'lint': LintCommand,
|
||||
},
|
||||
)
|
||||
|
||||
123
tests.py
123
tests.py
@@ -1,123 +0,0 @@
|
||||
import unittest
|
||||
from markdownify import markdownify as md
|
||||
|
||||
|
||||
class BasicTests(unittest.TestCase):
|
||||
|
||||
def test_single_tag(self):
|
||||
self.assertEqual(md('<span>Hello</span>'), 'Hello')
|
||||
|
||||
def test_soup(self):
|
||||
self.assertEqual(md('<div><span>Hello</div></span>'), 'Hello')
|
||||
|
||||
def test_whitespace(self):
|
||||
self.assertEqual(md(' a b \n\n c '), ' a b c ')
|
||||
|
||||
|
||||
class ArgTests(unittest.TestCase):
|
||||
|
||||
def test_strip(self):
|
||||
self.assertEqual(
|
||||
md('<a href="https://github.com/matthewwithanm">Some Text</a>', strip=['a']),
|
||||
'Some Text')
|
||||
|
||||
def test_do_not_strip(self):
|
||||
self.assertEqual(
|
||||
md('<a href="https://github.com/matthewwithanm">Some Text</a>', strip=[]),
|
||||
'[Some Text](https://github.com/matthewwithanm)')
|
||||
|
||||
def test_convert(self):
|
||||
self.assertEqual(
|
||||
md('<a href="https://github.com/matthewwithanm">Some Text</a>', convert=['a']),
|
||||
'[Some Text](https://github.com/matthewwithanm)')
|
||||
|
||||
def test_do_not_convert(self):
|
||||
self.assertEqual(
|
||||
md('<a href="https://github.com/matthewwithanm">Some Text</a>', convert=[]),
|
||||
'Some Text')
|
||||
|
||||
|
||||
class EscapeTests(unittest.TestCase):
|
||||
|
||||
def test_underscore(self):
|
||||
self.assertEqual(md('_hey_dude_'), '\_hey\_dude\_')
|
||||
|
||||
def test_xml_entities(self):
|
||||
self.assertEqual(md('&'), '&')
|
||||
|
||||
def test_named_entities(self):
|
||||
self.assertEqual(md('»'), u'\xbb')
|
||||
|
||||
def test_hexadecimal_entities(self):
|
||||
# This looks to be a bug in BeautifulSoup (fixed in bs4) that we have to work around.
|
||||
self.assertEqual(md('''), '\x27')
|
||||
|
||||
def test_single_escaping_entities(self):
|
||||
self.assertEqual(md('&amp;'), '&')
|
||||
|
||||
|
||||
class ConversionTests(unittest.TestCase):
|
||||
|
||||
def test_a(self):
|
||||
self.assertEqual(
|
||||
md('<a href="http://google.com">Google</a>'),
|
||||
'[Google](http://google.com)'
|
||||
)
|
||||
|
||||
def test_a_with_title(self):
|
||||
self.assertEqual(
|
||||
md('<a href="http://google.com" title="The "Goog"">Google</a>'),
|
||||
r'[Google](http://google.com "The \"Goog\"")'
|
||||
)
|
||||
|
||||
def test_b(self):
|
||||
self.assertEqual(md('<b>Hello</b>'), '**Hello**')
|
||||
|
||||
def test_blockquote(self):
|
||||
self.assertEqual(md('<blockquote>Hello</blockquote>').strip(), '> Hello')
|
||||
|
||||
def test_nested_blockquote(self):
|
||||
self.assertEqual(
|
||||
md('<blockquote>And she was like <blockquote>Hello</blockquote></blockquote>').strip(),
|
||||
'> And she was like \n> > Hello'
|
||||
)
|
||||
|
||||
def test_br(self):
|
||||
self.assertEqual(md('a<br />b<br />c'), 'a \nb \nc')
|
||||
|
||||
def test_em(self):
|
||||
self.assertEqual(md('<em>Hello</em>'), '*Hello*')
|
||||
|
||||
def test_h1(self):
|
||||
self.assertEqual(md('<h1>Hello</h1>'), 'Hello\n=====\n\n')
|
||||
|
||||
def test_h2(self):
|
||||
self.assertEqual(md('<h2>Hello</h2>'), 'Hello\n-----\n\n')
|
||||
|
||||
def test_hn(self):
|
||||
self.assertEqual(md('<h3>Hello</h3>'), '### Hello\n\n')
|
||||
self.assertEqual(md('<h6>Hello</h6>'), '###### Hello\n\n')
|
||||
|
||||
def test_i(self):
|
||||
self.assertEqual(md('<i>Hello</i>'), '*Hello*')
|
||||
|
||||
def test_ol(self):
|
||||
self.assertEqual(md('<ol><li>a</li><li>b</li></ol>'), '1. a\n2. b\n')
|
||||
|
||||
def test_p(self):
|
||||
self.assertEqual(md('<p>hello</p>'), 'hello\n\n')
|
||||
|
||||
def test_strong(self):
|
||||
self.assertEqual(md('<strong>Hello</strong>'), '**Hello**')
|
||||
|
||||
def test_ul(self):
|
||||
self.assertEqual(md('<ul><li>a</li><li>b</li></ul>'), '* a\n* b\n')
|
||||
|
||||
|
||||
class AdvancedTests(unittest.TestCase):
|
||||
|
||||
def test_nested(self):
|
||||
self.assertEqual(
|
||||
md('<p>This is an <a href="http://example.com/">example link</a>.</p>'),
|
||||
'This is an [example link](http://example.com/).\n\n'
|
||||
)
|
||||
0
tests/__init__.py
Normal file
0
tests/__init__.py
Normal file
39
tests/test_advanced.py
Normal file
39
tests/test_advanced.py
Normal file
@@ -0,0 +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'
|
||||
25
tests/test_args.py
Normal file
25
tests/test_args.py
Normal file
@@ -0,0 +1,25 @@
|
||||
"""
|
||||
Test whitelisting/blacklisting of specific tags.
|
||||
|
||||
"""
|
||||
from markdownify import markdownify as md
|
||||
|
||||
|
||||
def test_strip():
|
||||
text = md('<a href="https://github.com/matthewwithanm">Some Text</a>', strip=['a'])
|
||||
assert text == 'Some Text'
|
||||
|
||||
|
||||
def test_do_not_strip():
|
||||
text = md('<a href="https://github.com/matthewwithanm">Some Text</a>', strip=[])
|
||||
assert text == '[Some Text](https://github.com/matthewwithanm)'
|
||||
|
||||
|
||||
def test_convert():
|
||||
text = md('<a href="https://github.com/matthewwithanm">Some Text</a>', convert=['a'])
|
||||
assert text == '[Some Text](https://github.com/matthewwithanm)'
|
||||
|
||||
|
||||
def test_do_not_convert():
|
||||
text = md('<a href="https://github.com/matthewwithanm">Some Text</a>', convert=[])
|
||||
assert text == 'Some Text'
|
||||
13
tests/test_basic.py
Normal file
13
tests/test_basic.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from markdownify import markdownify as md
|
||||
|
||||
|
||||
def test_single_tag():
|
||||
assert md('<span>Hello</span>') == 'Hello'
|
||||
|
||||
|
||||
def test_soup():
|
||||
assert md('<div><span>Hello</div></span>') == 'Hello'
|
||||
|
||||
|
||||
def test_whitespace():
|
||||
assert md(' a b \t\t c ') == ' a b c '
|
||||
217
tests/test_conversions.py
Normal file
217
tests/test_conversions.py
Normal file
@@ -0,0 +1,217 @@
|
||||
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="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>') == '\n> Hello\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> \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_code():
|
||||
inline_tests('code', '`')
|
||||
assert md('<code>this_should_not_escape</code>') == '`this_should_not_escape`'
|
||||
|
||||
|
||||
def test_del():
|
||||
inline_tests('del', '~~')
|
||||
|
||||
|
||||
def test_div():
|
||||
assert md('Hello</div> World') == 'Hello World'
|
||||
|
||||
|
||||
def test_em():
|
||||
inline_tests('em', '*')
|
||||
|
||||
|
||||
def test_h1():
|
||||
assert md('<h1>Hello</h1>') == 'Hello\n=====\n\n'
|
||||
|
||||
|
||||
def test_h2():
|
||||
assert md('<h2>Hello</h2>') == 'Hello\n-----\n\n'
|
||||
|
||||
|
||||
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"),
|
||||
]
|
||||
for image_attributes, markdown in image_attributes_to_markdown:
|
||||
assert md('<h3>A <img src="/path/to/img.jpg " ' + image_attributes + '/> B</h3>') == '### A ' + markdown + ' 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_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'
|
||||
|
||||
|
||||
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'
|
||||
|
||||
|
||||
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'
|
||||
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**'
|
||||
23
tests/test_escaping.py
Normal file
23
tests/test_escaping.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from markdownify import markdownify as md
|
||||
|
||||
|
||||
def test_underscore():
|
||||
assert md('_hey_dude_') == r'\_hey\_dude\_'
|
||||
assert md('_hey_dude_', escape_underscores=False) == r'_hey_dude_'
|
||||
|
||||
|
||||
def test_xml_entities():
|
||||
assert md('&') == '&'
|
||||
|
||||
|
||||
def test_named_entities():
|
||||
assert md('»') == u'\xbb'
|
||||
|
||||
|
||||
def test_hexadecimal_entities():
|
||||
# This looks to be a bug in BeautifulSoup (fixed in bs4) that we have to work around.
|
||||
assert md(''') == '\x27'
|
||||
|
||||
|
||||
def test_single_escaping_entities():
|
||||
assert md('&amp;') == '&'
|
||||
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'
|
||||
150
tests/test_tables.py
Normal file
150
tests/test_tables.py
Normal file
@@ -0,0 +1,150 @@
|
||||
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_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_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>"""
|
||||
|
||||
|
||||
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_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_missing_text) == '\n\n| | Lastname | Age |\n| --- | --- | --- |\n| Jill | | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
assert md(table_missing_head) == '\n\n| | | |\n| --- | --- | --- |\n| Firstname | Lastname | Age |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
||||
Reference in New Issue
Block a user