Neculai Fântânaru

Everything Depends On The Leader

Python Save Title Html Tag To Link

On March 16, 2022
, in
Python Scripts Examples by Neculai Fantanaru

You can view the full code here: https://pastebin.com/qmpbmnMa

Install Python.

For example I have this page:

my-name-is-prince.html

And this html page has the title tag: <title>I love Freddy Mercury</title>

Output: After running the python code, I will parse and convert the title tag into link. Will become:

i-love-freddy-mercury.html with the same <title>I love Freddy Mercury</title>

from bs4 import BeautifulSoup
from bs4.formatter import HTMLFormatter
import requests
import re
import execjs
from urllib import parse
import json
import os

class UnsortedAttributes(HTMLFormatter):
    def attributes(self, tag):
        for k, v in tag.attrs.items():
            yield k, v


def read_text_from_file(file_path):
    """
    Aceasta functie returneaza continutul unui fisier.
    file_path: calea catre fisierul din care vrei sa citesti
    """
    with open(file_path, encoding='utf8') as f:
        text = f.read()
        return text


def write_to_file(text, file_path):
    """
    Aceasta functie scrie un text intr-un fisier.
    text: textul pe care vrei sa il scrii
    file_path: calea catre fisierul in care vrei sa scrii
    """
    with open(file_path, 'wb') as f:
        f.write(text.encode('utf8', 'ignore'))

files_from_folder = "e:\\Folder"

extension_file = ".html"

directory = os.fsencode(files_from_folder)

amount = 1
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    if filename == 'y_key_e479323ce281e459.html' or filename == 'directory.html':
        continue

    if filename.endswith(extension_file):
        current_file_name = ''
        new_file_name = ''

        with open(os.path.join(files_from_folder, filename), encoding='utf-8') as html:
            file_text = html.read()
            soup = BeautifulSoup('<pre>' + file_text + '</pre>', 'html.parser')
            text_title = soup.findAll('title')[0].get_text()

            print(f'{filename} changed filename ({amount})')
            amount += 1
            new_filename = text_title
            # replace 's
            new_filename = re.sub('\'\w', '', new_filename)
            new_filename = new_filename.lower()
            words = re.findall(r'\w+', new_filename)
            new_filename = '-'.join(words)
            new_filename = new_filename + '.html'
            new_filename = os.fsdecode(new_filename)

            # inlocuire nume fisier
            current_file_name = os.path.join(files_from_folder, filename)
            new_file_name = os.path.join(files_from_folder, new_filename)

            canonical_pattern = re.compile('<link rel="canonical" href="(.*?)" />')
            canonical = re.findall(canonical_pattern, file_text)
            if len(canonical) > 0:
                canonical = canonical[0]
                link_nou = "https://trinketbox.ro/en/" + '-'.join(words) + ".html"
                file_text = file_text.replace(canonical, link_nou)
                write_to_file(file_text, current_file_name)
            else:
                print("Nu am gasit tag-ul canonical in fisier")

        html.close()
        os.rename(current_file_name, new_file_name)

That's all folks.

Also, see this VERSION 2 or VERSION 3 or VERSION 4 or VERSION 5 or VERSION 6 or VERSION 7

Alatura-te Comunitatii Neculai Fantanaru
The 63 Greatest Qualities of a Leader
Cele 63 de calităţi ale liderului

Why read this book? Because it is critical to optimizing your performance. Because it reveals the main coordinates after that are build the character and skills of the leaders, highlighting what it is important for them to increase their influence.

Leadership - Magic of Mastery
Atingerea maestrului

The essential characteristic of this book in comparison with others on the market in the same domain is that it describes through examples the ideal competences of a leader. I never claimed that it's easy to become a good leader, but if people will...

The Master Touch
Leadership - Magia măiestriei

For some leaders, "leading" resembles more to a chess game, a game of cleverness and perspicacity; for others it means a game of chance, a game they think they can win every time risking and betting everything on a single card.

Leadership Puzzle
Leadership Puzzle

I wrote this book that conjoins in a simple way personal development with leadership, just like a puzzle, where you have to match all the given pieces in order to recompose the general image.

Performance in Leading
Leadership - Pe înţelesul tuturor

The aim of this book is to offer you information through concrete examples and to show you how to obtain the capacity to make others see things from the same angle as you.

Leadership for Dummies
Leadership - Pe înţelesul tuturor

Without considering it a concord, the book is representing the try of an ordinary man - the author - who through simple words, facts and usual examples instills to the ordinary man courage and optimism in his own quest to be his own master and who knows... maybe even a leader.