Saravanan666/pypi-org huggingface dataset:
Package: htmldocx
htmldocxConvert html to docxDependencies:python-docx&bs4To installpip install htmldocxUsageAdd strings of html to an existing docx.Document objectfrom docx import Document
from htmldocx import HtmlToDocx

document = Document()
new_parser = HtmlToDocx()
# do stuff to document

html = '<h1>Hello world</h1>'
new_parser.add_html_to_document(html, document)

# do more stuff to document
document.save('your_file_name')Convert files directlyfrom htmldocx import HtmlToDocx

new_parser = HtmlToDocx()
new_parser.parse_html_file(input_html_file_path, output_docx_file_path)Convert files from a stringfrom htmldocx import HtmlToDocx

new_parser = HtmlToDocx()
docx = new_parser.parse_html_string(input_html_file_string)Change table stylesTables are not styled by default. Use thetable_styleattribute on the parser to set a table
style. The style is used for all tables.from htmldocx import HtmlToDocx

new_parser = HtmlToDocx()
new_parser.table_style = 'Light Shading Accent 4'To add borders to tables, use theTableGridstyle:new_parser.table_style = 'TableGrid'Default table styles can be found here:https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html#table-styles-in-default-template
Package: html_dsl
html-dslA HTML-DSL for PythonUSE>>> from html_dsl.elements import BaseHtmlElement
>>> from html_dsl.common import HTML, BODY, H1, P, DIV, SPAN
>>> html = HTML[
        BODY[
            H1["Title"],
            P(color="yellow")[
                "Hello, World.", SPAN["something in span"], "Out of the span"
            ],
            P["This is the second paragraph."],
            DIV[
                DIV(_class="row")[
                    DIV(_class="column", color="red")["col1"],
                    DIV(_class="column", color="blue")["col2"],
                    DIV(_class="column", color="green")["col3"],
                ]
            ],
        ]
    ]
>>> print(html)
<html>
  <body>
    <h1>
    Title
    </h1>
    <p color="yellow">
    Hello, World.
      <span>
      something in span
      </span>
    Out of the span
    </p>
    <p>
    This is the second paragraph.
    </p>
    <div>
      <div class="row">
        <div color="red" class="column">
        col1
        </div>
        <div color="blue" class="column">
        col2
        </div>
        <div color="green" class="column">
        col3
        </div>
      </div>
    </div>
  </body>
</html>Installpipinstallhtml_dslAuthorYixian Du
Package: html-element-attributes
HtmlElementAttributesPython port of npm packagehtml-element-attributes.List of known HTML tag attribute names.What is this?This is a list of HTML tag attribute names.Installpipinstallhtml-element-attributesUsefromHtmlTagNamesimporthtml_element_attributesprint(html_element_attributes["*"])Yields:['accesskey','autocapitalize','autofocus','class',//…'style','tabindex','title','translate']LicenseGPL© Riverside Healthcare
Ported fromhtml-element-attributesMIT© [Titus Wormer][https://github.com/wooorm]
Package: htmlement
HTMLementHTMLement is a pure Python HTML Parser.The object of this project is to be a “pure-python HTML parser” which is also “faster” than “beautifulsoup”.
And like “beautifulsoup”, will also parse invalid html.The most simple way to do this is to use ElementTreeXPath expressions.
Python does support a simple (read limited) XPath engine inside its “ElementTree” module.
A benefit of using “ElementTree” is that it can use a “C implementation” whenever available.This “HTML Parser” extendshtml.parser.HTMLParserto build a tree ofElementTree.Elementinstances.InstallRunpip install htmlement-or-pip install git+https://github.com/willforde/python-htmlement.gitParsing HTMLHere I’ll be using a sample “HTML document” that will be “parsed” using “htmlement”:html = """
<html>
  <head>
    <title>GitHub</title>
  </head>
  <body>
    <a href="https://github.com/marmelo">GitHub</a>
    <a href="https://github.com/marmelo/python-htmlparser">GitHub Project</a>
  </body>
</html>
"""

# Parse the document
import htmlement
root = htmlement.fromstring(html)Root is anElementTree.Elementand supports the ElementTree API
with XPath expressions. With this I’m easily able to get both the title and all anchors in the document.# Get title
title = root.find("head/title").text
print("Parsing: %s" % title)

# Get all anchors
for a in root.iterfind(".//a"):
    print(a.get("href"))And the output is as follows:Parsing: GitHub
https://github.com/willforde
https://github.com/willforde/python-htmlementParsing HTML with a filterHere I’ll be using a slightly more complex “HTML document” that will be “parsed” using “htmlement with a filter” to fetch
only the menu items. This can be very useful when dealing with large “HTML documents” since it can be a lot faster to
only “parse the required section” and to ignore everything else.html = """
<html>
  <head>
    <title>Coffee shop</title>
  </head>
  <body>
    <ul class="menu">
      <li>Coffee</li>
      <li>Tea</li>
      <li>Milk</li>
    </ul>
    <ul class="extras">
      <li>Sugar</li>
      <li>Cream</li>
    </ul>
  </body>
</html>
"""

# Parse the document
import htmlement
root = htmlement.fromstring(html, "ul", attrs={"class": "menu"})In this case I’m not unable to get the title, since all elements outside the filter were ignored.
But this allows me to be able to extract all “list_item elements” within the menu list and nothing else.# Get all listitems
for item in root.iterfind(".//li"):
    # Get text from listitem
    print(item.text)And the output is as follows:Coffee
Tea
Milk
Package: htmlentities
HTML Entities for PythonInstallingFor install python-htmlentities, run on terminal:$ [sudo] pip install htmlentitiesUsing htmlentitiesencodingYou can encode a char to your htmlentitie relative usingencodemethod:import htmlentities

htmlentities.encode('<') # returns "&lt"decodingYou can decode a htmlentitie to your relative char usingdecodemethod:import htmlentities

htmlentities.decode('&lt') # returns "<"developmentSource hosted atGitHubReport issues onGitHub IssuesPull requests are very welcomed! Make sure your patches are well tested.running the testsif you are using a virtualenv, all you need is:$ make testcommunityirc channel#cobrateam channel on irc.freenode.net
Package: htmlentitiesdecode
This module makes it easy to decode html entities in strings.Licensehtmlentitiesdecode is free software under the terms of the Do What The
Fuck You Want To Public License version 2 (or any later version). The
author of htmlentities is Niels Serup, contactable atns@metanohi.org. This is version 0.1.1 of the program.InstallingIf you have python-setuptools installed, you can just do this:$ sudo easy_install htmlentitiesdecodeAlternatively, download and extract the gzipped tarball found on this
very page, and then run this:$ sudo python setup.py installThe newest version ofhtmlentitiesdecodeis always available athttp://metanohi.org/projects/htmlentitiesdecode/and at the Python
Package Index.UsingThis module has only one main function:decode. Example usage:>>> from htmlentitiesdecode import decode as entity_decode
>>> print entity_decode('Wie hei&szlig;t du?')
Wie heißt du?
>>> print entity_decode('Ich hei&#223;e "htmlentitiesdecode".')
Ich heiße "htmlentitiesdecode".
>>> print entity_decode('Wir hei&#x00DF;en "modules".')
Wir heißen "modules".RunningWhen this module has been installed, you will have both a module and a
command-line script that uses the decode function of the module. This
script can be run this way:$ decodehtmlentities TEXTChangelogVersion 0.1.0: Initial releaseVersion 0.1.1: Fixed error in README
Package: htmler
HTMLerHTMLer is a simple HTML generation library for Python.Build statusFeaturesEasy and flexible to use.Outputs beautifully indented codeRequirementsPython >=3.6InstallationpipinstallhtmlerUsageThis example:fromhtmlerimportHtml,Head,Body,Meta,Title,Script,Link,P,Adoc=Html(Head(Meta(charset='utf-8'),Title('Hello World Document'),Script(src='main.js'),Link(rel='stylesheet',src='main.css'),),Body(P(A('Hello World!',href="https://en.wikipedia.org/wiki/%22Hello,_World!%22_program"))),lang="en",)print(doc)will provide following output:<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8"><title>Hello World Document</title><scriptsrc="main.js"></script><linkrel="stylesheet"src="main.css"></head><body><p><ahref="https://en.wikipedia.org/wiki/%22Hello,_World!%22_program">Hello World!</a></p></body></html>If indentation is not necessary, just callrender()method withindentargument set toFalse:print(doc.render(indent=False))DocumentationWork in progress.Testingpythonsetup.pytestormaketestContributingIf you want to contribute to a project and make it better, your help is very
welcome. Contributing is also a great way to learn more about social coding on
Github, new technologies and and their ecosystems and how to make constructive,
helpful bug reports, feature requests and the noblest of all contributions:
a good, clean pull request.Create a personal fork of the project on Github.Clone the fork on your local machine. Your remote repo on Github is calledorigin.Add the original repository as a remote calledupstream.If you created your fork a while ago be sure to pull upstream changes into
your local repository.Create a new branch to work on. Branch fromdevelopif it exists, else frommaster.Implement/fix your feature, comment your code.Follow the code style of the project, including indentation.If the project has tests run them.Write or adapt tests as needed.Add or change the documentation as needed.Squash your commits into a single commit with git's interactive rebase. Create
a new branch if necessary.Push your branch to your fork on Github, the remoteorigin.From your fork open a pull request in the correct branch. Target the project'sdevelopbranch if there is one, else go formaster.If the maintainer requests further changes just push them to your branch.Once the pull request is approved and merged you can pull the changes fromupstreamto your local repo and delete your extra branch(es).And last but not least: Always write your commit messages in the present tense.
Your commit message should describe what the commit, when applied, does to the
code – not what you did to the code.RoadmapWrite documentation.SupportIf you have any issues or enhancement proposals feel free to report them via
project'sIssue Tracker.AuthorsOleksandr Shepetko-- initial work.CreditsThis project was inspired byPyHTMLlibrary.LicenseThis project is licensed under the MIT License. See theLICENSE.mdfile for details.
Package: htmlextradata
MkDocs-htmlextradata-pluginПлагин MkDocs, который вводит дополнительную переменнуюextradataв html-шаблон. Данная переменная попадает в контекст страницы, если файл .yml называется так же ка странца .mdУстановкаУстановите пакет с помощью pip или poetry:pipinstallhtmlextradata

or

poetryaddhtmlextradataВключите плагин в вашем "mkdocs.yml`:plugins:-search-htmlextradataилиplugins:-search-htmlextradata:data:path/to/datafilesПо умолчанию он будет искать в папке, где хранится ваш mkdocs.yml, и в папке docs другую папку с именем _extradata (т.е. ./docs/_extradata/mtrs.yaml), доступную в шаблоне как {{ extradata }}, если есть страница с таким именем.
Package: htmlfactory
htmlfactoryA simple way to produce HTML with Python.
Source code can be found ongithub.pipinstallhtmlfactoryhtmlfactorysimplifies the process of making HTML through Python.Examples:basic div exampleTagFactory("div.my-class")<divclass='my-class'></div>To add content between the divs, we can pass a string orTagFactoryobjects.# pass a stringTagFactory("div.my-class",'I am inside the div.')<divclass='my-class'>I am inside the div.</div># pass a TagFactory objectTagFactory("div.my-class",TagFactory("div","child tag"))<divclass="my-class"><div>child tag</div></div>children div examplepass a list ofTagFactoryobjectsTagFactory("div.parent-div",[TagFactory("div.first-child-div",(TagFactory("div.second-child-div","It's party time.")))])<divclass='parent-div'><divclass='first-child-div'><divclass='second-child-div'>It's party time.</div></div></div>Note:
Children tags can be passed through a list, tuple, or singularTagFactoryobject.printingTagFactoryobjectsTo output a TagFactory object, use print.print(TagFactory('div',TagFactory('form')))<div><form></form></div>Use the functionpretty_str()for an indented output.print(TagFactory('div',TagFactory('form')).pretty_str())<div><form></form></div>If you would like an HTML, body, and head tag to be included, passadd_html_tags=True.print(TagFactory('div',TagFactory('form')).pretty_str(add_html_tags=True))<html><head></head><body><div><form></form></div></body></html>multiple classes exampleYou can add as many classes as you want to your tag object:TagFactory("div.class1.class2.class3.class4.class5",'I have a lot of classes.')<divclass='class1 class2 class3 class4 class5'>I have a lot of classes.</div>adding attributes exampleYou can add attributes to your tab object by using keyword arguments:TagFactory("form",'I have an action & method attribute.',action="/action_page.php",method="get")<formaction='/action_page.php'method='get'>I have an action and method attribute.</form>Note:
'for' is a keyword so it cannot be used as a keyword argument. Instead use 'four'.
Example:TagFactory("div.my-class", "inside the div", four="my-form")Dashes (-) also cause a similar problem. For all html attributes that require a dash,
omit the dash. The dash will be added upon creation of the object.# with an omitted dashTagFactory("div",role="application",ariadescribedby="info")<divrole='application'aria-describedby='info'></div>adding tags without closing brackets exampleYou can create tags without closing brackets, which may be useful if wanting to add an img or link:test_tag=SingletonTag("img",border="0",alt="TestTag",src="logo_w3s.gif",width="100",height="100")<imgborder='0'alt='TestTag'src='logo_w3s.gif'width='100'height='100'>The SingletonTag class is inherited to the TagFactory class, so SingletonTags can be treated like TagFactory objects and added as children html elements to other TagFactory objects.a_tag=TagFactory("a",SingletonTag("img",src="logo_w3s.gif"),href="www.google.com")<ahref='www.google.com'><imgsrc='logo_w3s.gif'></a>
Package: htmlfilter
AboutVery simple white list HTML filter.Use it with a WYSIWYG editor on the client side.Usage::from htmlfilter import HTMLFilter
hf = HTMLFilter()
cleaned_html = hf.filter(dirty_html)Rules fileThe filter is instanciated with a predefined set of rules.http://github.com/samueladam/htmlfilter/blob/master/htmlfilter/rules.pyYou can create your own rules file:# file: my_rules.py
TAGS = {
        'a': ('href', 'name',),
        'p': ('class',),
}

# define filters on attributes data (tag_attr)
def p_class(data):
    if data not in ('class1', 'class2',):
        data = ''
    return dataAnd use them this way:from htmlfilter import HTMLFilter
import my_rules

hf = HTMLFilter(rules=my_rules)
cleaned_html = hf.filter(dirty_html)
Package: html-for-docx
HTML FOR DOCXConvert html to docx, this project is a fork from descontinuedpqzx/html2docx.How installpip install html-for-docxUsageThe basic usage: Add HTML formatted to an existing Docxfromhtml4docximportHtmlToDocxparser=HtmlToDocx()html_string='<h1>Hello world</h1>'parser.add_html_to_document(html_string,filename_docx)You can usepython-docxto manipulate the file as well, here an examplefromdocximportDocumentfromhtml4docximportHtmlToDocxdocument=Document()new_parser=HtmlToDocx()html_string='<h1>Hello world</h1>'new_parser.add_html_to_document(html_string,document)document.save('your_file_name')Convert files directlyfromhtml4docximportHtmlToDocxnew_parser=HtmlToDocx()new_parser.parse_html_file(input_html_file_path,output_docx_file_path)Convert files from a stringfromhtml4docximportHtmlToDocxnew_parser=HtmlToDocx()docx=new_parser.parse_html_string(input_html_file_string)Change table stylesTables are not styled by default. Use thetable_styleattribute on the parser to set a table style. The style is used for all tables.fromhtml4docximportHtmlToDocxnew_parser=HtmlToDocx()new_parser.table_style='Light Shading Accent 4'To add borders to tables, use theTableGridstyle:new_parser.table_style='TableGrid'Default table styles can be found
here:https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html#table-styles-in-default-templateWhyMy goal to fork and fix/update this package was to complete my current task at work that envolves manipulating a html to docs which the original couldn't complete because was lacking of few features and bugs, so instead creating a package from zero, I prefer update this one.Differences (fixes and new features)FixesHandle missing run for leading br tag |dashingdovefromPRFix base64 images |djplanerfromIssueHandle img tag without src attribute |johnjorfromPRFix bug when any style has!important|Dfop02Fix 'style lookup by style_id is deprecated.' |Dfop02New FeaturesAdd Witdh/Height style to images |maifeeulasadfromPRSupport px, cm, pt and % for style margin-left to paragraphs |Dfop02Improve performance on large tables |dashingdovefromPRSupport for HTML Pagination |EvilranfromPRSupport Table style |EvilranfromPRSupport alternative encoding |HebaElwazzanfromPRRefactory Tests to be more consistent and less 'human validation' |Dfop02LicenseThis project is licensed under the MIT License - see theLICENSEfile for details
Package: html-form-to-dict
HTML Form to DictThis is a tiny library which provides a method calledhtml_form_to_dict().This method takes a string containing HTML and returns a dictionary of the values of the first form.The data returned byhtml_form_to_dict()is aFormDictwhich has the methodsubmit(). This way
you can submit the data like a real browser would.This mean you can do simple end-to-end testing of form handling without a real browser (like selenium/puppeteer/playwright).Thesubmit()method supports the "action" and "method" attributes of forms and additionaly thehtmxattributeshx-get,hx-post.Example:def test_foo(client):
    ...
    
    # client is a DjangoClient. But you could use
    # python-requests or a different URL-lib, too
    response = client.get(url)
    
    # This method parses the HTML in response.content to a dictionary.
    # This dictionary is like request.POST or request.GET.
    # It is a flat mapping from the input elements of the form
    # to their value.
    data = html_form_to_dict(response.content)
    
    # Now you can test the default values of the form.
    assert data == {'city': 'Chemnitz', 'name': 'Mr. X'}
    
    # You can edit the data. This is like a human (or Playwright/Selenium)
    # altering the HTML input fields
    data['name'] = 'Mrs. Y'
    
    # This submits the data to the server.
    # This methods uses the "action" attribute of the form.
    # The hx-get, hx-post attributes of htmx are supported, too
    response = data.submit(client)
    
    # If you use the Post/Redirect/Get pattern:
    assert response.status == 302, response.context['form'].errorsAbove code uses pytest-django. Seeclient fixtureTheFormDictreturned byhtml_form_to_dict()does not allow adding new
keys, which are not in the dictionary yet. This way you get an error if your
test sets the value for an input which (maybe due to refactoring) does not exist.Above example uses Django, but the library is a pure Python library which does not depend on any
particular web-framework.This library was build for testing, but you can use it for all tasks where you
want to parse and submit html forms.This library does not evaluate JavaScript. If you need JS support, please use Playwright (or a similar tool).Installpipinstallhtml_form_to_dictDevelopmentYou need to upload your ssh-pub-key to github first:pipinstall-egit+ssh://git@github.com/guettli/html_form_to_dict#egg=html_form_to_dict
edit-the-code
pipinstallpytest
pytest
createPull-RequestAlternativesMechanizeThis library is like a browser without JS support.You could use BeautifulSoup like explained in thisStackoverflow AnswerUsePlaywrightfor browser based end-to-end tests.Deployvia deploy-library.pyfor py2 tgz package:python -m twine upload dist/html_form_to_dict-*.tar.gz
Package: html-for-nlp
HTML for NLPInstallationpipinstallgit+https://github.com/druskacik/html_for_nlpUsageimportrequestsfromhtml_for_nlpimportHTMLDocumentr=requests.get('https://google.com')doc=HTMLDocument(r.content)print(doc.full_text)Output:<[document]>
Google
Vyhľadávanie
<a>
Obrázky
</a>
<a>
Mapy
</a>
<a>
Play
</a>
<a>
YouTube
</a>
<a>
Správy
</a>
<a>
Gmail
</a>
<a>
Disk
</a>
<a>
Ďalšie
»
</a>
<a>
História hľadania
</a>
|
<a>
Nastavenia
</a>
|
<a>
Prihlásiť sa
</a>
<a>
Rozšírené vyhľadávanie
</a>
<span>
<a>
Reklama
</a>
<a>
Riešenia pre firmy
</a>
<a>
Všetko o Google
</a>
<a>
Google.sk
</a>
<p>
© 2023
</p>
</span>
</[document]>
Package: html-from-epub
HTML from EpubExtract html library from .epub file.Install$pipinstallhtml_from_epubUseCommand line tool script will install along with Python package.$html-from-epubpath_to_file.epubUse in code:>>>fromhtml_from_epubimportconvert>>>convert('path_to_file.epub')ContributeGo ahead:$gitclonehttps://github.com/casperlehmann/html_from_epub.git
$cdhtml_from_epub
$pipinstall-rrequirements.txt
Package: htmlfun
htmlfun.py
Helper functions for generating HTML documents.Usage:>>> from htmlfun.elements import html, body, h1
>>> from htmlfun import build_doc>>> content = body(h1({"class": "header"}, "Hello, world!"))
>>> doc = build_doc(content)
>>> print(doc)HTML elements are represented as nested lists of strings. These lists
can be flattened using the flatten() core function and joined together
into an html document. The build_doc() helper function is a wrapper
around flatten() that wraps your tags in an HTML5 declaration and a
root <html> tag pair.
Package: htmlfy
htmlfyPython package for HTML minification.Installationpython3-mpipinstallhtmlfyUsageMinifing HTML markup in variable>>>importhtmlfy>>>html="""<!DOCTYPE html><html><head><title>Hello</title></head><body><p>hello, world!</p></body></html>""">>>htmlfy.minify_html(html)'<!DOCTYPE html><html><head><title>Hello</title></head><body><p>hello, world!</p></body></html>'Minifing HTML file>>>importhtmlfy>>>src_path='my_file.html'>>>dst_path='my_file.min.html'>>>htmlfy.minify_html_file(src_path,dst_path)Argumentsdefhtmlfy.minify_html(html,strict_spaces=True,no_space_between_tags=True,preserve=True,remove_comments=True,html5_min_attr=True,html5_emptytags=True)defminify_html_file(source_path,minified_path,strict_spaces=True,no_space_between_tags=True,preserve=True,remove_comments=True,html5_min_attr=True,html5_emptytags=True)strict_spaces- strict all spaces(new lines, tabs and etc.) to single space. Except preserved blocks.no_space_between_tags- delete all spaces between tags.preserve- it will save all formating in<pre>,<textarea>,<script>tags. Also it will keep PHP expresions like<?php ... ?>and<?=...?>remove_comments- delete all types of comments from the code also from<style>and<script>like<!-- ... -->,/* ... */or// comment. You can save the comment using<!--! ... -->format. Expressions comments like<!--[if gte IE 7]>...<![endif]-->will be preserved also.html5_min_attr- shrinkdisabled="disabled",checked="checked",selected="selected"to HTML5 notationdisabled,checkedandselectedhtml5_emptytags- removes tailing slash in empty tags like<br />,<img ... />or<input ... />LicenseCopyright (c) 2019, Alexey SchebelevDistributed underThe BSD 3-Clause License.