Как связать html с Python?
У меня есть HTML код, который запускается как веб приложение на aiohttp(python). Как обратиться к данным, которые вводит пользователь? То есть мне необходимо интегрировать введенные данные в мой скрипт на языке Python, как это сделать?
const sendMessage = () =>
html < font-family: Verdana, "sans-serif"; >body < min-height: 100vh; background: black no-repeat; >h1 < text-align: center; color: white; text-shadow: 0 3px 5px rgba(150, 150, 150, 0.8); >#root < display: flex; flex-direction: column; align-items: center; >#messages < width: 70%; >.message < background-color: white; width: 100%; padding: 20px; border-radius: 10px; -webkit-transition: 0.3s; -moz-transition: 0.3s; transition: 0.3s; -webkit-box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.1); box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.1); box-sizing: border-box; margin-bottom: 10px; >.message:hover < -webkit-transition: 0.3s; -moz-transition: 0.3s; transition: 0.3s; -webkit-box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.5); -moz-box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.5); box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.5); >.message__created < font-size: 12px; color: darkgrey; text-align: right; >.message__text < font-size: 20px; color: black; margin-top: 5px; >.message__ratings < display: flex; justify-content: space-between; font-size: 16px; font-weight: 400; margin-top: 5px; >.form < width: 70%; margin-bottom: 20px; display: flex; flex-direction: column; gap: 20px; >.form__button < text-align: center; margin-top: 150px; background-color: white; cursor: pointer; >.form__input, .form__button < box-sizing: border-box; width: 100%; font-size: 18px; outline: none; border: none; padding: 20px; border-radius: 15px; -webkit-transition: 0.3s; -moz-transition: 0.3s; transition: 0.3s; -webkit-box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.1); box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.1); >.form__input:focus, .form__button:hover
Port Scanner
Scan
PyScript — Python, встроенный в HTML
PyScript — средство запуска Python в браузере, встроенное в HTML, был анонсирован на мероприятии PyCon в Солт-Лейк-Сити, США.

Кнопка Instl здесь для шутки, так как установка не требуется
PyScript зависит от существующего проекта Pyodide, который является скомпилированным в WebAssembly интерпретатором CPython 3.8, позволяющим запускать Python в браузере, а также скомпилированных научных пакетов Python.
Связывание с файлами библиотеки CSS и JavaScript PyScript позволяет разработчикам встраивать код Python с помощью тега , а также компонент (Read, Evaluate, Print, Loop), который позволяет Python печатать и выполняться динамически.
PyScript является открытым исходным кодом с использованием лицензии Apache 2.0.
Согласно сайту проекта, цели включают в себя включение Python в браузере без настройки на стороне сервера, запуск популярных пакетов Python, двунаправленную связь между JavaScript и Python и визуальную разработку с использованием «легкодоступных контролируемых компонентов пользовательского интерфейса, таких как кнопки, контейнеры, текстовые поля и многое другое».
Упрощение использования в браузере порадует не только ученых, разрабатывающих аналитические приложения, но и программистов любого профиля, ищущих альтернативу JavaScript — хотя разработчики проекта предупреждают, что это «чрезвычайно экспериментальный проект» и что он только проверен в веб-браузере Google Chrome.
Please be advised that PyScript is very alpha and under heavy development. There are many known issues, from usability to loading times, and you should expect things to change often. We encourage people to play and explore with PyScript, but at this time we do not recommend using it for production.
Туториал PyScript
Попробуем скачать, настроить и запустить приложение PyScript в браузере.
Рабочая среда
Разработчики PyScript пишут, что для работы не требуется никакой среды разработки, кроме веб-браузера. Попробуем запустить в Chrome.
Установка
Можно скачать весь пакет с сайта, но будем использовать скрипт, с сервера pyscript.net
Hello World
Создаем файл hello.html
html> head> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> head> body> py-script> print('Hello, World!') py-script> body> html>
Тег расположен внутри HTML body. Внутри этого тега будем пиcать Python код.
Откроем файл в браузере

Тег py-script
Тег позволяет писать многострочный код
html> head> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> head> body> py-script> print("Let's compute π:") def compute_pi(n): pi = 2 for i in range(1,n): pi *= 4 * i ** 2 / (4 * i ** 2 - 1) return pi pi = compute_pi(100000) s = f"π is approximately " print(s) py-script> body> html>
Важно соблюдать отступы в самом блоке Python. Но Начальную строку кода можно начинать и с начала строки
html> head> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> head> body> py-script> print("Let's compute π:") def compute_pi(n): pi = 2 for i in range(1,n): pi *= 4 * i ** 2 / (4 * i ** 2 - 1) return pi pi = compute_pi(100000) s = f"π is approximately " print(s) py-script> body> html>
Запись внутри HTML элементов
В приведенном выше примере у нас был один тег , выводящий одну или несколько строк на страницу по порядку. Внутри есть доступ к модулю pyscript, который предоставляет метод .write() для отправки строк в помеченные элементы на странице.
Например, мы добавим некоторые элементы стиля и предоставим заполнители для тега для записи.
html> head> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous"> head> body> b>p>Today is u>label id='today'>label>u>p>b> br> div id="my-custom-pi" class="alert alert-primary">div> py-script> import datetime as dt pyscript.write('today', dt.date.today().strftime('%A %B %d, %Y')) def compute_pi(n): pi = 2 for i in range(1,n): pi *= 4 * i ** 2 / (4 * i ** 2 - 1) return pi pi = compute_pi(100000) pyscript.write('my-custom-pi', f'π is approximately ') py-script> body> html>

Тег py-env
В дополнение к стандартной библиотеке Python и модулю pyscript, многие сторонние пакеты работают с PyScript. Чтобы их использовать, нужно объявить зависимости с помощью тега в заголовке HTML. Вы также можете ссылаться на файлы .whl прямо на диске
py-env> - './static/wheels/travertino-0.1.3-py3-none-any.whl' - './static/wheels/my-other-package-0.0.1-py3-none-any.whl' py-env> py-script> #my python code . py-script>
Пример с NumPy
html> head> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> py-env> - numpy - matplotlib py-env> head> body> h1>Let's plot random numbersh1> div id="plot">div> py-script output="plot"> import matplotlib.pyplot as plt import numpy as np x = np.random.randn(1000) y = np.random.randn(1000) fig, ax = plt.subplots() ax.scatter(x, y) fig py-script> body> html>
Импорт локальный модулей
Мы также можем использовать собсвтенные модули, которые импортируем внутри тега
Например, создадим файл `data.py’ и запишем в него собственную функцию
# data.py import numpy as np def make_x_and_y(n): x = np.random.randn(n) y = np.random.randn(n) return x, y
Внутри тега добавим стандартные модули и путь до нашего локального модуля
html> head> link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> script defer src="https://pyscript.net/latest/pyscript.js">script> py-env> - numpy - matplotlib - paths: - /data.py py-env> head> body> h1>Let's plot random numbersh1> div id="plot">div> py-script output="plot"> import matplotlib.pyplot as plt from data import make_x_and_y x, y = make_x_and_y(n=1000) fig, ax = plt.subplots() ax.scatter(x, y) fig py-script> body> html>
Тег py-repl
Тег создает компонент REPL(Read–eval–print loop), который отображается на странице как редактор кода, что позволяет писать исполняемый код в строке.
Тег py-config
Тег используется для установки и настройки общих метаданных о вашем приложении PyScript в формате YAML.
py-config> - autoclose_loader: false - runtimes: - src: "https://cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js" name: pyodide-0.20 lang: python py-config>
Тег py-title
Тег визуального отображения. Добавляет компонент заголовка статического текста, который стилизует текст внутри тега как заголовок страницы.
Тег py-box
Создает объект-контейнер, который можно использовать для размещения одного или нескольких визуальных компонентов, определяющих, как элементы должны выравниваться и отображаться на странице.
Тег py-inputbox
Позволяет вставить окно с текстовым полем
Тег py-button
Добавляет кнопку, к которой авторы могут добавлять метки и обработчики событий для действий на кнопке, таких как on_focus или on_click.
Ресурсы
- Примеры использования PyScript
- Вопросы по PyScript
Ребят, как мне объединить Python + Html + Css?
Ребят , кароче , начал программировать и вот создал базу на Python + html на пайтоне , на сайте есть комменты , статьи и ТД , вот только надо это сделать красиво я знаю как пользоваться css только не знаю как подключить его к пайтону + html . И да , мб на пайтоне (Джанго ) нужно создать только базу а весь сайт на html делать , и там уже к html css подключить ? И как запустить этот сайт а своем пк ( хостинг ). Или же можно верстать на самом Python ? Заранее спасибо !
- Вопрос задан более трёх лет назад
- 7103 просмотра
3 комментария
Простой 3 комментария

Rustam Bainazarov @SmthTo Куратор тега CSS
Верстать на Python нельзя. Верстают на HTML, CSS и JS.
Python может быть использован только для генерации оных в роли шаблонизатора.
Герман Хакер @omaxkarpov Автор вопроса
Рустам Байназаров, хорошо , а как к пайтону подключить css

Rustam Bainazarov @SmthTo Куратор тега CSS
Герман Хакер, без понятия. Отдельным файлом или ещё как-нибудь. Не знаю, как у вас устроена архитектура всего.
Решения вопроса 4

Диванный разработчик
Попробуй фреймворк Flask
Ответ написан более трёх лет назад
Комментировать
Нравится 1 Комментировать
Пишу роботов на html
На Питоне сайт не сверстаешь. Нужно создать шаблоны на html и css подключать к соответствующей странице html. Посмотри уроки по Django у Гоши Дударя, там он всё подробно рассказывает.
Ответ написан более трёх лет назад

SKEPTIC @pro100chel Куратор тега Python
У дудки много корявых уроков, ничему не учит. Лучше смотреть нормальные каналы. Смотрю у Гошана — ничего не понимаю, смотрю у тру ютуберов — все ок, схватываю с полу слова.
Но некоторые уроки у Гошки все-таки есть нормальные.
Кто, по-твоему, «тру ютубер»?
Pro100Chel, Хауди хо 😀
Герман Хакер @omaxkarpov Автор вопроса
iiideb, Братан , я знаю что к хтмл надо , я так делал но почему то все также изменения не выводились , все было ОК
Вам прямая дорога в документацию к Django, там отличный туториал и в нем написано как нужно работать с шаблонами и статикой.
PS Файлы стилей(css) вообще никак не связаны с питоном, они подключаются в html-шаблонах, а отдаются на продакшене веб-сервером напрямую.
Ответ написан более трёх лет назад
Комментировать
Нравится Комментировать

Мне кажется, вопрос можно перефразировать так: как мне научиться работать с Джанго?
И тут всё очень индивидуально, зависит от того, как вам проще и удобнее:
— самостоятельная разработка на основании документации + придуманных вами себе задач (или боевого проекта),
— бесплатные уроки на Ютуб,
— платные курсы, как минимум, на Юдеми за 800-1000 рублей можно взять видеокурс, где вас за руку проведут через создание одного приложения на Джанго,
— платные курсы по дороже — контор много, рекламы тоже, учить будут несколько месяцев, возьмут десятки тысяч, наверное,
— опытный наставник — он сам составит план вашего обучения, будет ставить задачи и направлять, но. есть у вас такой под рукой?
Один совет: будете выбирать материалы в сети — выбирайте свежую версию Джанго!
И ещё момент: для локальной разработки ничего придумывать не надо — сервер у Джанго в коробке. Вопросом деплоя я бы задавался не сразу, а после того, как у вас будет хоть первое работающее локально приложение.
HTML and CSS for Python Developers

When you want to build websites as a Python programmer, there’s no way around HTML and CSS. Almost every website on the Internet is built with HTML markup to structure the page. To make a website look nice, you can style HTML with CSS.
If you’re interested in web development with Python, then knowing HTML and CSS will help you understand web frameworks like Django and Flask better. But even if you’re just getting started with Python, HTML and CSS can enable you to create small websites to impress your friends.
In this tutorial, you’ll learn how to:
- Structure a basic HTML file
- View and inspect HTML in your browser
- Insert images and page links
- Style a website with CSS
- Format HTML with accessibility in mind
- Use Python to write and parse HTML code
You’ll get an introduction to HTML and CSS that you can follow along with. Throughout this tutorial, you’ll build a website with three pages and CSS styling:

Your browser displays the text without complaining. It seems the browser can handle an HTML file, even if its only cue is the extension. That’s good to know, but this behavior also has a downside.
Browsers will always try to render HTML documents, even when the HTML syntax of your document is not valid. Very seldomly, the browser itself will show you something like a SyntaxError, similar to what Python does when you try to run invalid code. This means that you may not notice if you’ve shipped invalid code, which can cause issues for your website visitors.
Note: If you want to validate the HTML code that you write, then you can upload your HTML file to W3C Markup Validation Service. This linting tool analyzes your code and points out errors.
Update index.html and create a minimal valid HTML document by adding the code below:
1 2 3 4html lang="en"> 5head> 6 meta charset="utf-8"> 7 title>Am I HTML already?title> 8head> 9html>
This code is the most minimal valid HTML document that you can get away with. Strictly speaking, you could even ditch the lang attribute in line 4. But adding the right language subtag is recommended to declare which natural language your document contains.
Note: In this tutorial, you’ll stick with English and use the en language tag. You can visit the official language subtag registry to find all the other language tags.
The language attribute makes it easier for translation tools to work with your website and will make your website more accessible. Screen readers in particular rely heavily on the language declaration of an HTML document to choose the right language mode for synthesizing the content.
At its root, any HTML document that you build will probably follow the structure of the example above. But there’s one important HTML element missing. Open index.html and add below :
1 2 3 4html lang="en"> 5head> 6 meta charset="utf-8"> 7 title>Am I HTML already?title> 8head> 9body> 10Yes,br>I am! 11body> 12html>
Any valid HTML file must start with a doctype declaration. In this tutorial, you’ll be using , which tells the browser that the document contains HTML5 code and should render your page in standard mode:
If a browser finds an outdated, incomplete or missing doctype at the start of the page, they use “quirks mode”, which is more backwards compatible with old practices and old browsers. (Source)
After the doctype declaration, you have an opening tag. In line 12, you can find the corresponding closing tag. Most elements in HTML have an opening tag, some content in between, and a closing tag at the end. These parts can even be on the same line, like the element in line 7.
Other elements, like in line 6, don’t have a matching closing tag, so they don’t contain any content. These empty elements are so-called void elements. They stand independently and may not even contain attributes. One such example is
in line 10, which creates a line break.
HTML tags start with an angle bracket ( < ) and end with an angle bracket ( >). The tag names in between the angle brackets are usually pretty descriptive and state what the HTML element is meant for. A good example is in line 7, in which the content defines the title of your page.
The block contains the mass of your content. You can think of as the part of the HTML document that you can interact with in your browser.
Sometimes the tag names are abbreviated, like the line break element
in line 10. To get an overview of other HTML tag names, visit Mozilla’s HTML elements reference.
Once you’ve familiarized yourself with the structure of your HTML document, reload index.html in your browser and check out how your website looks:

Awesome, you’re now displaying the content of your first proper website!
There’s a good chance that you’ll start any web project with a structure like the one that you’ve built in this section. To save yourself some work in the future, you can download the HTML boilerplate code by clicking the link below:
Free Bonus: Click here to download the supplemental materials for this tutorial, including a time-saving HTML template file.
In the next section, you’ll improve the base structure that you’ve created so far. To explore why HTML is called a markup language, you’ll add content and structure to your website.
Whitespace and Text Formatting
The only markup that your HTML document has so far is the base skeleton of your website. Now it’s time to dive in deeper and structure some real content. To have something to work with, add the text below to the block of index.html :
1 2 3 4html lang="en"> 5head> 6 meta charset="utf-8"> 7 title>Am I HTML already?title> 8head> 9body> 10Hello, World Wide Web! 11This is my first website. 12 13About me 14 15I'm a Python programmer and a bug collector. 16 17Random facts 18 19I don't just like emoji, 20I love emoji! 21 22My most-used emoji are: 23 1. 24 2. 25 3. 26 27Links 28 29My favorite websites are: 30 * realpython.com 31 * python.org 32 * pypi.org 33body> 34html>
When you open the website in your browser, it seems that the browser didn’t recognize any whitespace at all. Although you distributed your content on multiple lines inside , the browser displays everything as one continuous line:

As a Python developer, you know that whitespace is a vital ingredient in writing beautiful Python code. The indentation of your Python code makes a difference in how Python executes your code.
Without any additional adjustments, browsers collapse multiple spaces, line breaks, or indentation to one space character. To format your content differently, you must provide further information to the browser. Go ahead and structure index.html by adding HTML tags to your content:
1 2 3 4html lang="en"> 5head> 6 meta charset="utf-8"> 7 title>Am I HTML already?title> 8head> 9body> 10h1>Hello, World Wide Web!h1> 11p>This is my first website.p> 12 13h2>About meh2> 14p>I'm a Python programmer and a bug collector.p> 15 16h3>Random factsh3> 17p>I don't just em>likeem> emoji,br> 18I strong>lovestrong> emoji!p> 19p>My most-used emoji are:p> 20ol> 21 li>li> 22 li>li> 23 li>li> 24ol> 25 26h2>Linksh2> 27p>My favorite websites are:p> 28ul> 29 li>realpython.comli> 30 li>python.orgli> 31 li>pypi.orgli> 32ul> 33body> 34html>
By wrapping your text in HTML blocks, you give the browser additional information about your intentions for the content. First, have a look at the HTML elements that wrap bigger chunks of text:
| Line | HTML Element | Description |
|---|---|---|
| 10 | Main headline of your website | |
| 11 | Paragraph, to structure text and related content | |
| 13 | Second-level headline, nested below | |
| 16 | Third-level headline, nested below | |
| 20 | Ordered list, typically rendered as a numbered list | |
| 28 | Unordered list, typically rendered with bullets ( • ) |
You can nest headline elements six levels deep. While you usually only have one element, you may have multiple to tags. Headline elements section your HTML document and are vitally important for screen readers. For example, readers may want to jump from headline to headline to navigate your content.
To write valid and accessible HTML, you must ensure that you don’t skip a headline level in your code. You can think of the headline tags like doors that open onto different floors of a building. One floor can have multiple exits to other floors. But remember, you can’t build a third floor if you don’t have a second floor yet. In other words, there can never be an element on your page unless you’ve first declared .
Some of the HTML elements that you used above contain text only. Others contain additional HTML elements that structure the content further:
| Line | HTML Element | Description |
|---|---|---|
| 17 | Emphasizes content | |
| 18 | Indicates important content | |
| 21 | List item, must be contained in a list element |
All HTML tags convey meaning. Therefore, it’s vitally important to carefully choose which markup you use for portions of your content. When you use the right semantics, then you enable everybody to consume your content the way that you intended. You make your website accessible for all:
The Web is fundamentally designed to work for all people, whatever their hardware, software, language, location, or ability. When the Web meets this goal, it is accessible to people with a diverse range of hearing, movement, sight, and cognitive ability. (Source)
Some HTML elements are pretty straightforward. For paragraphs, you use
. Other elements are a bit harder to grasp:
Example: When to use strong instead of em Show/Hide
Kushagra Gour provides a great summary in his blog entry Strong vs Em:
If it’s just visual importance, you want strong . If it alters the sentence meaning, use em .
In other words, em means that you would emphasize the word while speaking. For example, if someone said, “You don’t look bad,” you might wonder, “But do I smell bad?” The placement of emphasis is key to the meaning of the sentence.
If you simply want to draw the reader’s attention to a piece of vocabulary, for example, then you’d probably want to use strong instead.
When in doubt, don’t hesitate to search for HTML names on the Web. You’ll find discussions and usage notes about any HTML element.
Additionally, your browser’s default styling of HTML can give a decent impression by styling elements differently:

With markup, you add meaning to your website’s content. Writing semantically correct HTML is important for understanding your content.
Using proper semantics in your HTML document isn’t just helpful for the browser. It also makes the rendered HTML page accessible for users who consume your content with text-to-speech software.
If you want to learn more about modern HTML, then HTML5 Doctor is a great resource. To learn more about accessibility, you can check out Google’s course on making the Web accessible to all.
Links, Images, and Tables
Jumping from one website to another is an essential part of the Internet. These references are called hyperlinks, commonly referred to as links. Without links, websites would exist in a silo, and you could only access them if you knew the web address.
Also, you wouldn’t be able to navigate among multiple pages of a website if you didn’t have links that connected the pages. To connect the HTML documents that you’ve created so far, add a navigation menu to your HTML source code:
html lang="en"> head> meta charset="utf-8"> title>Am I HTML already?title> head> body> nav> a href="emoji.html">Emojia> nav> body> html>
With relative links, you can reference files in your directory tree. You may expect to see a URL whenever you have a link, but that’s not the case with relative links.
In this case, you link to a file named emoji.html . The browser understands that it can find emoji.html in the same directory and completes the full URL for you. That way, you don’t need to worry about changing any absolute paths when you decide to deploy your web project at some point.
So far, emoji.html doesn’t exist. To fix this, create a new file named emoji.html next to index.html :
html lang="en"> head> meta charset="utf-8"> title>My favorite emojititle> head> body> nav> a href="index.html">Homea> nav> h1>My favorite emojih1> p>I don't just em>likeem> emoji,br> I strong>lovestrong> emoji!p> p>Here's a list of my most-used emoji:p> ol> li>li> li>li> li>li> ol> body> html>
The structure of emoji.html is similar to index.html . The content of in emoji.html is almost identical to the random facts section of index.html , except that you changed the headline and moved it up one level to be .
At the top of , you also have a element. This time, however, you’re linking to index.html .
Next, create a new folder named images/ inside of your project directory and add a file named gallery.html :
1 2 3 4html lang="en"> 5head> 6 meta charset="utf-8"> 7 title>Image gallerytitle> 8head> 9body> 10nav> 11 a href="../index.html">Homea> 12 a href="../emoji.html">Emojia> 13nav> 14h1>Image galleryh1> 15body> 16html>
You’ll add some images to gallery.html in a moment. But first, have a look at lines 11 and 12, where you link to your other pages.
Because index.html and emoji.html are one folder above gallery.html , you must prefix the link target with two dots ( .. ) and a slash ( / ).
For more convenient access, you can also add a link to your gallery in the navigation menu of index.html :
html lang="en"> head> meta charset="utf-8"> title>Am I HTML already?title> head> body> nav> a href="emoji.html">Emojia> a href="images/gallery.html">Gallerya> nav>
You can also link to your gallery in emoji.html :
html lang="en"> head> meta charset="utf-8"> title>My favorite emojititle> head> body> nav> a href="index.html">Homea> a href="images/gallery.html">Gallerya> nav>
If you add a link to an HTML page, then you always have to think about navigating there from the file that you’re in right now. The gallery.html file is one directory below index.html in a folder named images/ . So when you’re linking to gallery.html , then you need to include the subfolder in the link, which you’ve done above.
Relative links are useful for linking pages of your website. When you want to add external links, then you use absolute links:
h2>Linksh2> p>My favorite websites are:p> ul> li>a href="https://www.realpython.com">realpython.coma>li> li>a href="https://www.python.org">python.orga>li> li>a href="https://www.pypi.org">pypi.orga>li> ul>
Instead of linking to HTML files, you’re linking to absolute web addresses in your list of favorite websites. These links are the same ones that you’d type into your browser’s address bar.
Hop to the browser and navigate around your website with the links that you just added:

Images are a great way to make your website more visually appealing. However, the image gallery is a bit all over the place, and without any additional styling, the website looks rather old-school. It’s time to change that!
In the next section, you’ll add styling rules to your HTML and gain better control over how the elements on your website look.
Style Your Content With CSS
When you open a plain HTML file in the browser, the browser adds some styling by default. That’s why you were able to differentiate the elements in the previous section although you didn’t add any styling yourself.
That’s basically a service from the browser to you as a human. But strictly speaking, when you write HTML, you only define the markup of your website. Pure HTML doesn’t provide any styling for the elements on your page. To style elements, you need to add CSS.
CSS stands for Cascading Style Sheets. As you’ll see later, you can combine and nest your CSS styling rules, hence the name cascading style sheets.
Just like HTML, it’s a cornerstone technology of the Internet. It helps you to separate the look of your website from the actual content:
In addition to having good semantics and an attractive layout, your content should make logical sense in its source order — you can always place it where you want using CSS later on, but you should get the source order right to start with, so what screen reader users get read out to them will make sense. (Source)
In this section, you’ll learn how to take control of your website’s styling by adding CSS.
Add Color to Your Website
So far, you’ve only used the browser to load your HTML file. But web browsers are powerful tools, and they can help you tremendously when you develop a website.
You can investigate any website with the developer tool pane of your browser. Especially when you work with CSS, your browser’s developer tools come in handy:

You can use your browser’s developer tools to investigate which font was loaded. What if it’s not Helvetica or Arial? Hop to the comments below and let the Real Python community know which font your system loads!
If you want to have more control over the displayed font, then you need to load custom web fonts. How to use @font-face in CSS is a great guide on implementing custom web fonts on your website.
With the CSS that you’ve added to your HTML, you’re only scratching the surface of designing your website. There are almost infinite ways of styling your content with CSS. If you want to dive in deeper, then you can check out Mozilla’s CSS reference.
Separate Your Concerns
You added the CSS code from the previous section directly into index.html with the help of the element. If you wanted to style emoji.html the same way, then you’d need to copy and paste the code.
As a Python developer, you know that copy and pasting code isn’t the best idea. You end up with the same code in two places, which makes updating your code cumbersome.
In your Python code, you can import modules to prevent repeating yourself. HTML offers similar functionality to load external resources into your HTML code. This allows you to load an external CSS file and refer to this style sheet from your HTML files.
Create a new file named style.css next to index.html and emoji.html . Then, cut the content of from index.html and paste it into style.css :
1/* style.css */ 2 3body 4 background-color: rgb(20, 40, 60); 5 color: rgb(240, 248, 255); 6 font-family: "Helvetica", "Arial", sans-serif; 7 font-size: 1.3em; 8> 9 10a 11 color: rgb(255, 111, 111); 12>
Note that your CSS file contains only the CSS declarations. In a CSS file, you don’t need the tag that you used to wrap your CSS code in index.html .
Also, spot the syntax of CSS comments in line 1. A forward slash followed by an asterisk ( /* ) indicates the start of a comment. You can distribute a CSS comment over multiple lines. You close the comment with another asterisk followed by a forward slash ( */ ).
Now you can reference style.css in the head of your index.html file:
html lang="en"> head> meta charset="utf-8"> title>Am I HTML already?title> link rel="stylesheet" href="style.css"> . --> head>
Add the stylesheet link to emoji.html as well:
html lang="en"> head> meta charset="utf-8"> title>My favorite emojititle> link rel="stylesheet" href="style.css"> head>
To reflect the changes in gallery.html too, add the relative link to style.css :
1 2 3 4html lang="en"> 5head> 6 meta charset="utf-8"> 7 title>Image Gallerytitle> 8 link rel="stylesheet" href="../style.css"> 9head> 10 11
Remember that style.css is one directory above gallery.html , which is in your images/ directory. So instead of just linking to style.css , you must link to ../style.css .
Once you’ve updated the CSS references, have a look at your pages in the browser:

You combined the style rules of your local style.css and the external simple.css . Play around with the order of how you load the external style sheets. When you reload your pages, you’ll spot that the appearance of your website changes.
Similar to overwriting variables in Python, CSS properties overwrite each other. Generally speaking, the last value that’s applied to an element wins.
In this section, you learned that you can use an external style sheet instead of the element. There’s even a third way to add CSS rules to your HTML. You can use a style HTML attribute to style HTML elements directly. This is called inline CSS styling.
Note: Inline CSS styling has its use cases. But when you start learning HTML and CSS, try to refrain from using it. In general, adding inline CSS is considered bad practice.
Being more explicit in connecting your CSS declarations with specific HTML elements can give you the control that you need to perfect your design. In the next section, you’ll learn how to style elements more flexibly with CSS classes.
Use Classes for Greater Flexibility
The CSS rules that you’ve set so far have only targeted generic HTML elements. But you can be much more specific with your CSS code when you set rules for HTML attributes.
Adding a class attribute to an HTML element enables you to use CSS class selectors to style elements based on their class values.
An essential characteristic of CSS classes is that they allow you to group common elements and apply a set of rules to all of them in one go, and then potentially update them while keeping the style consistent.
For example, you can define a class that applies rounded corner to images. But instead of targeting all image elements by using the img name, you can assign a class to only those images that should have rounded corners. This gives you the additional advantage of being able to add rounded corners to other elements by giving them the same class.
To learn how CSS class selectors work, adjust the code in gallery.html so it looks like this:
1 2 3 4head> 5 meta charset="utf-8"> 6 title>Image Gallerytitle> 7 link rel="stylesheet" href="https://cdn.simplecss.org/simple.css"> 8 link rel="stylesheet" href="../style.css"> 9head> 10 11 12 13h1>Image Galleryh1> 14div class="gallery rounded"> 15 img src="sky_1.png" alt="Cloudy sky." class="rounded"> 16 img src="sky_2.png" alt="Sun shining through a cloudy sky." class="rounded"> 17 img src="sky_3.png" alt="Sky with almost no clouds." class="rounded"> 18div> 19
First, remember to add a link to your external style sheets. Don’t forget to prepend the two dots to link to ../style.css because the style sheet is one folder above gallery.html .
Then, you’re wrapping the elements in a block. The element is a generic element for structuring your page. It doesn’t contain any semantic meaning, and you should only use it when no other HTML tag is more appropriate to use.
You also add class attributes to your HTML elements. In line 14, you’re even chaining classes in a space-separated list. This means that you apply two CSS classes to the element. In contrast, the elements in lines 15 to 17 only contain one CSS class.
To create the classes, head over to style.css and add this CSS code:
1/* style.css */ 2 3/* . */ 4 5.gallery 6 background: rgba(255, 255, 255, 0.2); 7 padding: 1em; 8> 9 10.rounded 11 border-radius: 15px; 12> 13 14.gallery img 15 margin-right: 0.2em; 16 width: 150px; 17>
You refer to CSS classes in the HTML class attribute without a dot ( . ). In your CSS code, however, you must add a dot at the beginning of a selector to specify that you’re targeting the class attributes. If you want to read more about CSS selectors, then head over to Mozilla’s CSS selectors documentation.
In lines 6 and 7, you set the rules for .gallery , like a partly transparent background and a 1em padding to add space to all sides inside of the gallery element.
With the .rounded selector, you give all HTML elements that contain this class a rounded corner with a radius of fifteen pixels.
You can even chain your CSS selectors as you do in line 14. With the space-separated selector list .gallery img , you’re adding a rule for all img elements inside an HTML element with the class gallery . With your CSS declarations in lines 15 and 16, you give them some space to the right side with margin-right and make the gallery images 150 pixels wide.
With padding , margin , and border properties, you define the spacing of CSS elements. You can think of these elements as boxes that have a certain space around them and space inside of them where the content is stored. This concept is called the box model:
Everything in CSS has a box around it, and understanding these boxes is key to being able to create more complex layouts with CSS, or to align items with other items. (Source)
If you want to dive deeper into CSS, then learning about the box model is key. You can follow Mozilla’s learn to style HTML using CSS tutorial to get a better understanding of all the building blocks that CSS contains.
You can take off from here and explore the world of markup and design that HTML and CSS offer. But especially with HTML, you’ll soon notice that it’s a very verbose language, and it can be cumbersome to write it by hand. That’s where you can let your skills as a Python developer shine.
In the next section, you’ll learn how Python can help you to work with HTML files more effectively.
Handle HTML With Python
As a Python developer, you know that Python can be a great tool to automate tasks that you’d otherwise need to do by hand. Especially when working with large HTML files, the power of Python can save you some work.
Programmatically Write HTML
With all the opening and closing tags, HTML can be cumbersome to write. Luckily, Python is perfect to help you programmatically create large HTML files.
In this section, you’ll extend emoji.html to display more information about your favorite emoji. Replace the ordered list with a table:
1 2 3 4h1>My favorite emojih1> 5p>I don't just em>likeem> emoji,br> 6I strong>lovestrong> emoji!p> 7p>Here's a table of my most-used emoji:p> 8 9table> 10 thead> 11 tr> 12 th>#th> 13 th>Emojith> 14 th>Nameth> 15 tr> 16 thead> 17 tbody> 18 tr> 19 td>1.td> 20 td>td> 21 td>Lady Beetletd> 22 tr> 23 tr> 24 td>2.td> 25 td>td> 26 td>Snaketd> 27 tr> 28 tr> 29 td>3.td> 30 td>td> 31 td>Thumbs Up Signtd> 32 tr> 33 tbody> 34table> 35
In your table head, you define three table columns by adding three elements to the first row.
The emoji table lists your three favorite emoji with their Unicode descriptions. Of course, nobody has only three favorite emoji!
Even with a moderate number like twelve favorite emoji, it’d be annoying to create the HTML table by hand. So you add Python into the mix!
Create a new Python file named emoji_table.py in your project directory, and let Python do the work for you:
# emoji_table.py import unicodedata all_emoji = "✨" columns = ["#", "Emoji", "Name"] table_head = f" \n ''.join(columns)> \n " table_body = "\n \n" for i, emoji in enumerate(all_emoji, start=1): emoji_data = [f"i>.", emoji, unicodedata.name(emoji).title()] table_body += f" ''.join(emoji_data)> \n" table_body += "\n" print(f" \ntable_head>table_body> ")
With the help of the built-in unicodedata module and enumerate() , Python can programmatically build an emoji table for you.
Note: The newline symbols ( \n ) in the strings are optional. The browser will ignore any whitespace that’s more than one space. But using \n will make your HTML code a bit prettier.
Run emoji_table.py in your terminal, copy the HTML code, and paste it into emoji.html :
1 2 3 4h1>My favorite emojih1> 5p>I don't just em>likeem> emoji,br> 6I strong>lovestrong> emoji!p> 7p>Here's a table of my most-used emoji:p> 8 9table> 10thead> 11tr>th>#th>th>Emojith>th>Nameth>tr> 12thead> 13tbody> 14tr>td>1.td>td>td>td>Lady Beetletd>tr> 15tr>td>2.td>td>td>td>Snaketd>tr> 16tr>td>3.td>td>td>td>Thumbs Up Signtd>tr> 17tr>td>4.td>td>td>td>Party Poppertd>tr> 18tr>td>5.td>td>td>td>Grinning Face With Star Eyestd>tr> 19tr>td>6.td>td>td>td>Face With Tears Of Joytd>tr> 20tr>td>7.td>td>td>td>Dog Facetd>tr> 21tr>td>8.td>td>td>td>Popcorntd>tr> 22tr>td>9.td>td>td>td>Smiling Face With Sunglassestd>tr> 23tr>td>10.td>td>✨td>td>Sparklestd>tr> 24tr>td>11.td>td>td>td>Speech Balloontd>tr> 25tr>td>12.td>td>td>td>Face Throwing A Kisstd>tr> 26tbody> 27table> 28
With emoji_table.py , you can now expand your HTML emoji table to include all your favorite emoji.
If you want to make your table look a bit better, then you can add additional styling with the :nth-child() pseudo-class in style.css :
/* style.css */ /* . */ th, tr:nth-child(even) background-color: rgba(255, 255, 255, 0.2); > td:nth-child(1) text-align: right; > td:nth-child(2) text-align: center; >
HTML tables are a great way to structure tabular data on your website. You can check out Mozilla’s documentation about HTML tables and styling tables to learn more about working with tables in HTML.
Although emoji_table.py helps you build larger tables, it’s still a complicated process. Currently, you need to copy the terminal output into your HTML file. That’s not ideal.
But now it’s time to explore other ways that Python can help you with your HTML code.
Create HTML Entities With Python
HTML comes with a big list of named character references that you can use to encode your texts in HTML. So, for example, you could write the euro currency sign as the HTML entity € instead of the UTF-8 € character.
In the past, encoding characters like this was important because there was no way to type them directly. With the advent of UTF-8 character encoding, you can use the actual UTF-8 character instead. Most of the time, that’s even recommended because it’s more readable.
Still, there are situations where HTML encodings are the better choice. As a rule of thumb, you use HTML entities when characters:
- Are visually not distinguishable
- Interfere with HTML syntax
Take whitespace characters, for example. There are twenty-five whitespace characters listed in the Unicode character database. Some of them look exactly the same, like the regular space ( ) and the non-breaking space ( ). Visually, the spaces are not distinguishable. But when you have a look at the source code of this page, you’ll see that the latter is escaped as its HTML entity, :

If you want to display HTML tags on an HTML document, you also need to escape characters like the opening angle bracket ( < ) and the closing angle bracket ( >). Again, have a look at the source code of this tutorial and note how the angle brackets are escaped:

The opening angle brackets are escaped as < . Closing angle brackets are escaped as > .
To see a full list of HTML entities, you can leverage Python’s built-in html module:
>>> import html >>> html.entities.html5 . 'zscr;': '', 'zwj;': '\u200d', 'zwnj;': '\u200c'>
The entities module of html defines four dictionaries. One of them is html5 , which maps the HTML-named character references to their Unicode character counterparts.
With html.entities.codepoint2name you can find the HTML entity name of a character:
>>> import html >>> code_point = ord("€") >>> code_point 8364 >>> html.entities.codepoint2name[cp] 'euro'
The codepoint of the euro ( € ) is 8364 . For 8364 the codepoint2name dictionary returns ‘euro’ . To use the name in your HTML code, you must put an ampersand ( & ) before the name and a semicolon ( ; ) after the name to get the valid € HTML entity.
Instead of remembering and writing the HTML entities yourself, you can let Python help you out. Python’s html module also comes with a parser that’s handy when you want to dissect HTML documents.
Parse HTML With Python
When you need to read data from HTML files, then Python can assist you with the built-in html module as well. In this section, you’ll build a primitive HTML parser using html.parser . The script you’ll write will refer to the gallery.html file that you created earlier in this tutorial. You can either revisit that part of the tutorial or download all the files by clicking the link below:
Free Bonus: Click here to download the supplemental materials for this tutorial, including a time-saving HTML template file.
Next to gallery.html , create a new Python file named parse_image_links.py :
# images/parse_image_links.py from html.parser import HTMLParser class ImageParser(HTMLParser): def handle_starttag(self, tag, attrs): for attr, val in attrs: if attr == "src" and tag == "img": print(f"Found Image: val!r>") with open("gallery.html", mode="r", encoding="utf-8") as html_file: html_content = html_file.read() parser = ImageParser() parser.feed(html_content)
When you feed an instance of Python’s HTMLParser with HTML data, the instance calls its handler methods if markup elements are found. In the example above, you create a subclass of HTMLParser to look for any elements with an src attribute in the code of gallery.html .
For the gallery.html file, the output looks like this:
Found Image: 'sky_1.png' Found Image: 'sky_2.png' Found Image: 'sky_3.png'
For your local file, which you can just look up in your editor, this might not be a big deal. But imagine the possibilities if you adjusted the script above to read the code from any given URL!
If Python’s html module has sparked your interest, then reading a practical introduction to web scraping in Python is a good next step. For a more hands-on approach, you can also build a web scraper with Beautiful Soup.
Before you parse away, have a look at some other next steps in the last section of this tutorial.
Continue With HTML and CSS in Python
You can accomplish quite a bit with basic HTML and CSS. Working with HTML and CSS can become even more fun when you put a programming language like Python into the mix.
In this section, you’ll get an overview of technologies that you may explore to leverage your knowledge of HTML and CSS.
JavaScript
As you learned in this tutorial, HTML provides the structure of a website. With CSS, you add formatting and layout. That’s a great basis for creating websites.
Yet no introduction to HTML and CSS would be complete without mentioning JavaScript. JavaScript is an interpreted programming language that’s crucial for modern websites.
With JavaScript, you can add functionality to your web projects. For example, you can dynamically update HTML and CSS when a user interacts with your website.
Learning JavaScript is a good choice for any programmer who wants to get into web development. To dive deeper into JavaScript, head over to Mozilla’s learning area for JavaScript.
If you want to explore JavaScript from a Python programmer’s perspective, then check out Python vs JavaScript for Pythonistas.
Jinja
In this tutorial, you stored HTML markup in Python strings to create HTML code dynamically. When your web project evolves, then the mix of HTML and Python can grow complicated.
To separate concerns, it’s a good idea to work with templates. With templates, you can create building blocks for larger websites without duplicating your front-end code. That way, you can keep your HTML markup in template files and fill them with Python. The go-to template engine for Python is Jinja.
With Python and Jinja, you can dynamically create HTML code. But you don’t have to stop there. Anytime you want to create text files with programmatic content, Jinja can help you out.
If you want to learn how to build rich templates with Jinja, then check out Real Python’s primer on Jinja templating.
Flask
With basic knowledge about HTML and CSS, you’re well equipped to build your first real web applications. HTML and CSS take care of the front end that the user is interacting with. To load the content from the server, you need some kind of back end. That’s where web frameworks come into play.
Flask is a popular Python web framework that’s great for building web applications from scratch. After you install the flask package with pip , then you start a Flask project by creating a Python file with just a few lines of code. In other words, you start small and enhance your project step by step at your own pace.
You can follow the Flask by Example learning path to discover the basics of Python web development with the Flask microframework.
Django
Django is another popular Python web framework. Compared to Flask, Django provides you with a project structure when you start a new Django project. Without adding much code yourself, you can work with an admin back end and databases right away. The power of Django can give you a head start for bigger web projects, but navigating all the files can be overwhelming for beginners.
Luckily, you can find plenty of Django tutorials on Real Python to guide you. You can get started with Django by building a portfolio app or by building a personal diary web app. If you want to build a bigger project, then the Django social network series is perfect for you.
PyScript
PyScript is a new framework that allows you to run Python in the web browser. But don’t confuse it with web frameworks like Flask or Django:
PyScript is just HTML, only a bit (okay, maybe a lot) more powerful, thanks to the rich and accessible ecosystem of Python libraries. (Source)
Conclusion
No matter which path to becoming a Python web developer you choose, there’s no way around HTML and CSS. Both technologies are fundamental building blocks when you want to create websites.
Throughout this tutorial, you built a boilerplate HTML document to give you a head-start in your upcoming web projects.
Along the way, you learned how to:
- Structure a basic HTML file
- Show images and link to pages
- Style a website with CSS
- Format HTML with accessibility in mind
- Use Python to write and parse HTML code
Python, HTML, and CSS are a powerful trio that enables you to create small HTML documents and big web projects. But even if you’re not aiming for a career as a web developer, knowing a thing or two about HTML and CSS will help you understand the Web better.
Free Bonus: Click here to download the supplemental materials for this tutorial, including a time-saving HTML template file.
