Creating html with python

domonic 0.9.11

Generate html with python 3. DOM API, Javascript API and more.

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License (MIT)

Метки html, generate, templating, dom, vdom, terminal, json, web, template, javascript, DOM, GUI, render, website, apps, html5, framework, SVG, x3d, events, geom

Требует: Python >=3.6

Сопровождающие

Классификаторы

  • Development Status
    • 4 — Beta
    • Web Environment
    • Developers
    • Other Audience
    • OSI Approved :: MIT License
    • English
    • OS Independent
    • JavaScript
    • Python
    • Python :: 3
    • Python :: 3.7
    • Python :: 3.8
    • Python :: 3.9
    • Python :: 3.10
    • Python :: 3.11
    • Internet
    • Internet :: WWW/HTTP
    • Internet :: WWW/HTTP :: Dynamic Content
    • Multimedia :: Graphics :: Presentation
    • Software Development
    • Software Development :: Code Generators
    • Software Development :: Libraries :: Python Modules
    • Terminals
    • Text Processing :: Markup :: HTML
    • Utilities

    Описание проекта

    𖤐 domonic 𖤐

    A DOM for making HTML with python 3! (and more)

    Install

    python3 -m pip install domonic  

    Creating HTML with Python 3

    or to pretty format and insert the doctype, use an f-string:

    from domonic import domonic To quickly parse a webapge try the window module.
    from domonic.window import window window.location Also try the xpath or css selectors on command line.

    More

    • html : Generate html with python 3 😎
    • dom : DOM API in python 3 😲
    • javascript : js API in python 3 😳 + (dQuery, d3)
    • JSON : utils for loading / decorating / transforming
    • SVG || mathml || aframe || x3d tags — generators for popular tags
    • terminal || cmd : call terminal commands with python3 😱

    See the docs/code for more features.

    Namespace

    Use the tags packaage if you want a namespace. i.e.

       or just import what you need.

    prepend attributes with an underscore ( avoids clashing with python keywords )

    domonic is a pure python dom whos tree is composed of objects. i.e

    cast str() on any element to render it without formatting.

    There’s also a render method that takes 2 parameters, some domonic and an optional output file.

    There’s a few new rendering options. See DOMConfig.

    DOM

    DOM manipulation with python.

    createElement

    to create your own elements use the DOM API

    There’s an evolving DOM API. To learn more about the webAPI click here.

    And check the code/docs to see what’s currently been implemented.

    To use the DOM either reference your root 'html' node or import the dom modules global 'document'
         There is a javascript package that mimics the js API:

    Use setInterval and clearInterval with params

    Or for a single delayed function call use setTimeout, clearTimeout
    You can call () on a stringvar to transform it into a Node

    For writing and using regular javascript, load from a src.

    or do inline js by opening triple quotes.

     Styling is supported. Styles get passed to the style tag on render.

    To use css use a link tag as you usually would.

    or use triple quotes to open style tag.
         use decorators to wrap elements around function results
    hi!
    It returns the tag object by default. You can pass True as a second param to the decorator to return a rendered string instead. Also accepts strings as first param i.e. custom tags.

    data-tags

    python doesn’t allow hyphens in parameter names. so use variable keyword argument syntax for custom data-tags

    JSON (utils)

    decorate any function that returns python objects to return json instead

    convert json arrays into html tables.

    ,] convert json arrays into csv files.
    convert csv files to json.

    SVG

    All tags extend ‘Element’. So will have DOM and magic methods available to them. See the docs.

    Tween values with the tween library:

    3d tags can be used if you import the js

    dQuery uses the º symbol (alt+0).

    Only recently started so check to see what’s implemented.

    terminal

    There is a command line package that can call bash/unix/posix and other apps on the command line:

    This package only works on nix systems as it effectively just passes stuff off to subprocess.

     or just run arbitrary commands.
    Take a look at the code in 'terminal.py' to see all the commands as there's loads. (Disclaimer: not all tested.)

    Windows users can use now use cmd.

    DOCS

    CLI

    Use the command line interface to help you out.

    To view the online the docs:

    To quickly create a domonic project for prototyping:

    To evaluate some domonic pyml:

    domonic -e To use xpath on a website from the command line:
    domonic -x https://google.com To use css selectors on a website from the command line:

    Blueberry : A browser based file OS. Working example of how components can work.

    htmlx : A low dependency lightweight (DOM only) version of domonic

    Checkout the docs for more examples i.e. generating sitemaps or using domonic with server frameworks like flask, django, sanic, fastapi and others.

    There’s also several useage examples in the repo so pull and have a look.

    Join-In

    Feel free to contribute if you find it useful. (I’d be grateful for help on all fronts)

    Email me, message me directly if you like or create a discussion on here. Or join the discord.

    If there are any methods you want that are missing or not complete yet or you think you can help make it better just update the code and send a pull request. I’ll merge and releaese asap.

    In the repo there’s a requirements-dev.txt which is mostly the libs used in the examples.

    requirements.txt are the libs used for packaging just the lib.

    See also the CONTRIBUTING.md

    running examples

    . venv/bin/activate pip install -r requirements-dev.txt 
    

    run tests

    There are tests used during dev. They are useful as code examples and to see what still needs doing.

    See Makefile to run all tests:

    or to test a single function:

    python -m unittest tests.test_javascript.TestCase.test_javascript_array python -m unittest tests.test_dQuery.TestCase.test_addClass python -m unittest tests.test_geom.TestCase.test_vec2 python3 -m unittest tests.test_cmd.TestCase.test_cmd_dir 

    or to test a whole module

    python -m unittest tests.test_html python -m unittest tests.test_CDN
    coverage run -m unittest discover tests/ coverage report
    pip install pytest pytest tests

    Disclaimer

    There's several more widely supported libraries doing HTML generation, DOM reading/manipulation, terminal wrappers etc. Maybe use one of those for production due to strictness and support.

    This is more of a fast prototyping library.

    Источник

    Creating and Viewing HTML Files with Python

    Child drawing on a tablet

    Here you will learn how to create HTML files with Python scripts, and how to use Python to automatically open an HTML file in Firefox.

    edited by

    reviewed by

    published

    modified

    difficulty

    DOI id icon

    https://doi.org/10.46430/phen0004

    Great Open Access tutorials cost money to produce. Join the growing number of people supporting Programming Historian so we can continue to share knowledge free of charge.

    Contents

    Lesson Goals

    This lesson uses Python to create and view an HTML file. If you write programs that output HTML, you can use any browser to look at your results. This is especially convenient if your program is automatically creating hyperlinks or graphic entities like charts and diagrams.

    Here you will learn how to create HTML files with Python scripts, and how to use Python to automatically open an HTML file in Firefox.

    Files Needed For This Lesson

    If you do not have these files from the previous lesson, you can download programming-historian-5, a zip file from the previous lesson.

    Creating HTML with Python

    At this point, we’ve started to learn how to use Python to download online sources and extract information from them automatically. Remember that our ultimate goal is to incorporate programming seamlessly into our research practice. In keeping with this goal, in this lesson and the next, we will learn how to output data back as HTML. This has a few advantages. First, by storing the information on our hard drive as an HTML file we can open it with Firefox and use Zotero to index and annotate it later. Second, there are a wide range of visualization options for HTML which we can draw on later.

    If you have not done the W3 Schools HTML tutorial yet, take a few minutes to do it before continuing. We’re going to be creating an HTML document using Python, so you will have to know what an HTML document is!

    “Hello World” in HTML using Python

    One of the more powerful ideas in computer science is that a file that seems to contain code from one perspective can be seen as data from another. It is possible, in other words, to write programs that manipulate other programs. What we’re going to do next is create an HTML file that says “Hello World!” using Python. We will do this by storing HTML tags in a multiline Python string and saving the contents to a new file. This file will be saved with an .html extension rather than a .txt extension.

    Typically an HTML file begins with a doctype declaration. You saw this when you wrote an HTML “Hello World” program in an earlier lesson. To make reading our code easier, we will omit the doctype in this example. Recall a multi-line string is created by enclosing the text in three quotation marks (see below).

    # write-html.py f = open('helloworld.html','w') message = """ 

    Hello World!

    """
    f.write(message) f.close()

    Save the above program as write-html.py and execute it. Use File -> Open in your chosen text editor to open helloworld.html to verify that your program actually created the file. The content should look like this:

    HTML Source Generated by Python Program

    Now go to your Firefox browser and choose File -> New Tab, go to the tab, and choose File -> Open File. Select helloworld.html . You should now be able to see your message in the browser. Take a moment to think about this: you now have the ability to write a program which can automatically create a webpage. There is no reason why you could not write a program to automatically create a whole website if you wanted to.

    Using Python to Control Firefox

    We automatically created an HTML file, but then we had to leave our editor and go to Firefox to open the file in a new tab. Wouldn’t it be cool to have our Python program include that final step? Type or copy the code below and save it as write-html-2.py . When you execute it, it should create your HTML file and then automatically open it in a new tab in Firefox. Sweet!

    Mac Instructions

    Mac users will have to specify to the precise location of the .html file on their computer. To do this, locate the programming-historian folder you created to do these tutorials, right-click it and select “Get Info”.

    You can then cut and paste the file location listed after “Where:” and make sure you include a trailing slash (/) to let the computer know you want something inside the directory (rather than the directory itself).

    # write-html-2-mac.py import webbrowser f = open('helloworld.html','w') message = """ 

    Hello World!

    """
    f.write(message) f.close() #Change path to reflect file location filename = 'file:///Users/username/Desktop/programming-historian/' + 'helloworld.html' webbrowser.open_new_tab(filename)

    If you’re getting a “File not found” error you haven’t changed the filename path correctly.

    Windows Instructions

    # write-html-2-windows.py import webbrowser f = open('helloworld.html','w') message = """ 

    Hello World!

    """
    f.write(message) f.close() webbrowser.open_new_tab('helloworld.html')

    Not only have you written a Python program that can write simple HTML, but you’ve now controlled your Firefox browser using Python. In the next lesson, we turn to outputting the data that we have collected as an HTML file.

    Suggested Readings

    Code Syncing

    To follow along with future lessons it is important that you have the right files and programs in your “programming-historian” directory. At the end of each lesson in the series you can download the “programming-historian” zip file to make sure you have the correct code. If you are following along with the Mac / Linux version you may have to open the obo.py file and change “file:///Users/username/Desktop/programming-historian/” to the path to the directory on your own computer.

    About the authors

    William J. Turkel is Professor of History at the University of Western Ontario.

    Adam Crymble, University College London.

    Suggested Citation

    William J. Turkel and Adam Crymble, "Creating and Viewing HTML Files with Python," Programming Historian 1 (2012), https://doi.org/10.46430/phen0004.

    Great Open Access tutorials cost money to produce. Join the growing number of people supporting Programming Historian so we can continue to share knowledge free of charge.

    The Programming Historian (ISSN: 2397-2068) is released under a CC-BY license.

    This project is administered by ProgHist Ltd, Charity Number 1195875 and Company Number 12192946.

    Источник

    Читайте также:  Css border image and border radius
Оцените статью