Skip to content

Instantly share code, notes, and snippets.

@relic-yuexi
Last active July 11, 2024 05:42
Show Gist options
  • Save relic-yuexi/6c0d3d7834565c9a45b602367491d14b to your computer and use it in GitHub Desktop.
Save relic-yuexi/6c0d3d7834565c9a45b602367491d14b to your computer and use it in GitHub Desktop.
Generate Random HTML Code With Python

With this code, you can easily generate some fake-html code.

pip install faker
import random
from faker import Faker
class HTMLGenerator:
"""
A class to generate random HTML content using Faker library.
"""
def __init__(self, language='en_US'):
"""
Initialize the HTMLGenerator with a specified language.
:param language: Language code for Faker, defaults to 'en_US'. \n
Other choices: `en_GB`, `zh_CN`, `ja_JP`, `ko_KR`, `de_DE`, `fr_FR`, `es_ES`, `it_IT`, etc.
"""
self.fake = Faker(language)
self.html_elements = [
self.generate_title,
self.generate_paragraphs,
self.generate_headers,
self.generate_unordered_list,
self.generate_ordered_list,
self.generate_description_list,
self.generate_blockquotes,
self.generate_code,
self.generate_preformatted_code,
self.generate_table,
self.generate_images,
self.generate_videos,
self.generate_audios,
self.generate_iframe,
self.insert_inline_elements,
]
def generate_html(self, target_length=1000, max_elements=10):
"""
Generate random HTML content up to a target length and maximum number of elements.
:param target_length: Target length of the HTML content
:param max_elements: Maximum number of HTML elements to generate
:return: Generated HTML content as a string
"""
random.shuffle(self.html_elements)
html_output = ""
current_length = 0
num_elements = 0
while current_length < target_length and num_elements < max_elements:
for element in self.html_elements:
if random.random() < 0.5:
element_html = element()
current_length += len(element_html)
html_output += element_html
num_elements += 1
if current_length >= target_length or num_elements >= max_elements:
break
if random.random() < 0.6:
html_output = self.insert_css(html_output)
if random.random() < 0.6:
html_output = self.insert_js(html_output)
return html_output
def generate_title(self):
"""Generate a random title (h1) element."""
return f"<h1>{self.fake.sentence()}</h1>\n"
def generate_paragraphs(self, num_paragraphs=1, min_sentences=2, max_sentences=10):
"""
Generate random paragraphs.
:param num_paragraphs: Number of paragraphs to generate
:param min_sentences: Minimum number of sentences per paragraph
:param max_sentences: Maximum number of sentences per paragraph
:return: HTML string containing paragraphs
"""
paragraphs_html = ""
for _ in range(num_paragraphs):
num_sentences = random.randint(min_sentences, max_sentences)
paragraph = self.fake.paragraph(nb_sentences=num_sentences)
paragraphs_html += f"<p>{paragraph}</p>\n"
return paragraphs_html
def generate_headers(self, num_headers=1, min_level=2, max_level=6):
"""
Generate random header elements (h2-h6).
:param num_headers: Number of headers to generate
:param min_level: Minimum header level (2-6)
:param max_level: Maximum header level (2-6)
:return: HTML string containing headers
"""
headers_html = ""
for _ in range(num_headers):
header_level = random.randint(min_level, max_level)
header_text = self.fake.sentence()
headers_html += f"<h{header_level}>{header_text}</h{header_level}>\n"
return headers_html
def generate_unordered_list(self, num_items=3, min_items=2, max_items=8):
"""
Generate a random unordered list.
:param num_items: Number of list items to generate
:param min_items: Minimum number of list items
:param max_items: Maximum number of list items
:return: HTML string containing an unordered list
"""
num_items = min(num_items, random.randint(min_items, max_items))
ul_html = "<ul>\n"
for _ in range(num_items):
ul_html += f" <li>{self.fake.sentence()}</li>\n"
ul_html += "</ul>\n"
return ul_html
def generate_ordered_list(self, num_items=3, min_items=2, max_items=8):
"""
Generate a random ordered list.
:param num_items: Number of list items to generate
:param min_items: Minimum number of list items
:param max_items: Maximum number of list items
:return: HTML string containing an ordered list
"""
num_items = min(num_items, random.randint(min_items, max_items))
ol_html = "<ol>\n"
for _ in range(num_items):
ol_html += f" <li>{self.fake.sentence()}</li>\n"
ol_html += "</ol>\n"
return ol_html
def generate_description_list(self, num_items=3, min_items=2, max_items=8):
"""
Generate a random description list.
:param num_items: Number of list items to generate
:param min_items: Minimum number of list items
:param max_items: Maximum number of list items
:return: HTML string containing a description list
"""
num_items = min(num_items, random.randint(min_items, max_items))
dl_html = "<dl>\n"
for _ in range(num_items):
dt = self.fake.word()
dd = self.fake.sentence()
dl_html += f" <dt>{dt}</dt>\n"
dl_html += f" <dd>{dd}</dd>\n"
dl_html += "</dl>\n"
return dl_html
def generate_blockquotes(self, num_quotes=1, min_quotes=1, max_quotes=3):
"""
Generate random blockquotes.
:param num_quotes: Number of blockquotes to generate
:param min_quotes: Minimum number of blockquotes
:param max_quotes: Maximum number of blockquotes
:return: HTML string containing blockquotes
"""
num_quotes = min(num_quotes, random.randint(min_quotes, max_quotes))
blockquotes_html = ""
for _ in range(num_quotes):
blockquotes_html += f"<blockquote>{self.fake.sentence()}</blockquote>\n"
return blockquotes_html
def generate_code(self):
"""Generate a random inline code element."""
return f"<code>{self.fake.text()}</code>\n"
def generate_preformatted_code(self):
"""Generate a random preformatted code block."""
return f"<pre><code>{self.fake.text()}</code></pre>\n"
def generate_table(self, num_rows=2, num_cols=2, max_rows=6, max_cols=4):
"""
Generate a random table.
:param num_rows: Number of rows in the table
:param num_cols: Number of columns in the table
:param max_rows: Maximum number of rows
:param max_cols: Maximum number of columns
:return: HTML string containing a table
"""
num_rows = min(num_rows, random.randint(1, max_rows))
num_cols = min(num_cols, random.randint(1, max_cols))
table_html = "<table>\n"
for _ in range(num_rows):
table_html += " <tr>\n"
for _ in range(num_cols):
table_html += f" <td>{self.fake.word()}</td>\n"
table_html += " </tr>\n"
table_html += "</table>\n"
return table_html
def generate_images(self, num_images=1, min_images=1, max_images=3):
"""
Generate random image elements.
:param num_images: Number of images to generate
:param min_images: Minimum number of images
:param max_images: Maximum number of images
:return: HTML string containing image elements
"""
num_images = min(num_images, random.randint(min_images, max_images))
images_html = ""
for _ in range(num_images):
img_url = self.fake.image_url()
img_alt = self.fake.word()
images_html += f'<img src="{img_url}" alt="{img_alt}">\n'
return images_html
def generate_videos(self, num_videos=1, min_videos=0, max_videos=2):
"""
Generate random video elements.
:param num_videos: Number of videos to generate
:param min_videos: Minimum number of videos
:param max_videos: Maximum number of videos
:return: HTML string containing video elements
"""
num_videos = min(num_videos, random.randint(min_videos, max_videos))
videos_html = ""
for _ in range(num_videos):
video_url = self.fake.url()
videos_html += f'<video src="{video_url}" controls></video>\n'
return videos_html
def generate_audios(self, num_audios=1, min_audios=0, max_audios=2):
"""
Generate random audio elements.
:param num_audios: Number of audio elements to generate
:param min_audios: Minimum number of audio elements
:param max_audios: Maximum number of audio elements
:return: HTML string containing audio elements
"""
num_audios = min(num_audios, random.randint(min_audios, max_audios))
audios_html = ""
for _ in range(num_audios):
audio_url = self.fake.url()
audios_html += f'<audio src="{audio_url}" controls></audio>\n'
return audios_html
def generate_iframe(self, num_iframes=1, min_iframes=0, max_iframes=2):
"""
Generate random iframe elements.
:param num_iframes: Number of iframes to generate
:param min_iframes: Minimum number of iframes
:param max_iframes: Maximum number of iframes
:return: HTML string containing iframe elements
"""
num_iframes = min(num_iframes, random.randint(min_iframes, max_iframes))
iframes_html = ""
for _ in range(num_iframes):
iframe_url = self.fake.url()
width = random.randint(200, 800)
height = random.randint(150, 600)
iframes_html += f'<iframe src="{iframe_url}" width="{width}" height="{height}" frameborder="0"></iframe>\n'
return iframes_html
def insert_inline_elements(self, paragraph=None):
"""
Insert random inline elements (links, bold, italic) into a paragraph.
:param paragraph: Paragraph to insert inline elements into (if None, generates a new paragraph)
:return: HTML string with inserted inline elements
"""
if paragraph is None:
paragraph = self.generate_paragraphs(num_paragraphs=1)
if random.random() < 0.3:
link_url = self.fake.url()
link_text = self.fake.word()
paragraph = paragraph.replace(link_text, f'<a href="{link_url}">{link_text}</a>', 1)
if random.random() < 0.3:
paragraph = paragraph.replace(self.fake.word(), f"<b>{self.fake.word()}</b>", 1)
if random.random() < 0.3:
paragraph = paragraph.replace(self.fake.word(), f"<i>{self.fake.word()}</i>", 1)
return paragraph
def insert_css(self, html):
"""
Insert random CSS styles into the HTML content.
:param html: HTML content to insert CSS into
:return: HTML string with inserted CSS
"""
css_code = f"""
body {{
background-color: {self.fake.hex_color()};
color: {self.fake.hex_color()};
}}
"""
return f"<style>{css_code}</style>\n{html}"
def insert_js(self, html):
"""
Insert random JavaScript code into the HTML content.
:param html: HTML content to insert JavaScript into
:return: HTML string with inserted JavaScript
"""
js_code = f"""
function {self.fake.word()}() {{
let {self.fake.word()} = {str(self.fake.random_int(1, 100))};
console.log({self.fake.word()});
}}
"""
return f"{html}\n<script>{js_code}</script>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment