Welcome to Warren Hance’s Ultimate SEO Coding Cheat Sheet! This guide provides you with essential scripts and code snippets to optimise your website for search engines. Each section includes a description, the relevant code, and clear instructions. Enjoy!
Subscriber Content
1. Meta Tags (HTML)
Description: Add essential meta tags for SEO.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<meta name=”description” content=”Your page description here”>
<meta name=”keywords” content=”keyword1, keyword2, keyword3″>
<meta name=”robots” content=”index, follow”>
<title>Your Page Title</title>
</head>
<body>
<!– Your content here –>
</body>
</html>
Instructions: Place the meta tags within the <head> section of your HTML document. Replace the placeholders with relevant content for your site.
2. Structured Data (JSON-LD)
Description: Add structured data for rich snippets.
html
<script type=”application/ld+json”>
{
“@context”: “https://schema.org”,
“@type”: “Organization”,
“name”: “Your Company Name”,
“url”: “https://www.yourwebsite.com”,
“logo”: “https://www.yourwebsite.com/logo.png”,
“contactPoint”: {
“@type”: “ContactPoint”,
“telephone”: “+1-800-555-5555”,
“contactType”: “Customer Service”
}
}
</script>
Instructions: Include this script within the <head> section of your HTML. Replace placeholder values with your organisation’s details.
3. SEO-Friendly URLs (Python with Flask)
Description: Create SEO-friendly URLs in a Flask app.
python
from flask import Flask, render_template
app = Flask(__name__)
@app.route(‘/product/<product_name>’)
def product_page(product_name):
return render_template(‘product.html’, product_name=product_name)
if __name__ == ‘__main__’:
app.run(debug=True)
Instructions: Define routes in your Flask app using descriptive URL patterns. The variable part of the URL (<product_name>) can be used within your views.
4. XML Sitemap (Python)
Description: Generate an XML sitemap.
python
import os
urls = [
‘https://www.yourwebsite.com/’,
‘https://www.yourwebsite.com/about/’,
‘https://www.yourwebsite.com/contact/’
]
with open(‘sitemap.xml’, ‘w’) as f:
f.write(‘<?xml version=”1.0″ encoding=”UTF-8″?>\n’)
f.write(‘<urlset xmlns=”http://www.sitemaps.org/schemas/sitemap/0.9″>\n’)
for url in urls:
f.write(‘ <url>\n’)
f.write(f’ <loc>{url}</loc>\n’)
f.write(‘ <priority>0.8</priority>\n’)
f.write(‘ </url>\n’)
f.write(‘</urlset>\n’)
Instructions: List your site’s URLs in the urls list. Run the script to generate an sitemap.xml file.
5. CSS for Readability
Description: Basic CSS for improving readability.
css
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 0;
color: #333;
}
h1, h2, h3 {
line-height: 1.2;
margin: 20px 0;
}
p {
margin: 12px 0;
padding: 0 20px;
}
Instructions: Include this CSS in your stylesheet to enhance text readability on your website.
6. Responsive Design (HTML + CSS)
Description: Make your site mobile-friendly.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.container {
max-width: 1200px;
margin: auto;
padding: 20px;
}
@media (max-width: 768px) {
.container {
padding: 10px;
}
}
</style>
</head>
<body>
<div class=”container”>
<h1>Responsive Design Example</h1>
<p>This is a simple example of responsive design.</p>
</div>
</body>
</html>
Instructions: Add the meta viewport tag in the <head> and use media queries in your CSS to adjust styles for different screen sizes.
7. Lazy Loading Images (JavaScript)
Description: Improve page load times with lazy loading.
html
<img class=”lazy” data-src=”image.jpg” alt=”Lazy Loaded Image”>
<script>
document.addEventListener(“DOMContentLoaded”, function() {
var lazyImages = [].slice.call(document.querySelectorAll(“img.lazy”));
if (“IntersectionObserver” in window) {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove(“lazy”);
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// Fallback for older browsers
lazyImages.forEach(function(lazyImage) {
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove(“lazy”);
});
}
});
</script>
Instructions: Add the lazy class and data-src attribute to your images. Include the JavaScript code to handle lazy loading.
8. Robots.txt
Description: Control how search engines crawl your site.
javascript
User-agent: *
Disallow: /private/
Allow: /public/
Sitemap: https://www.yourwebsite.com/sitemap.xml
Instructions: Place this file in the root directory of your website to specify which parts of your site search engines should crawl.
9. Canonical Tags (HTML)
Description: Avoid duplicate content issues.
html
<link rel=”canonical” href=”https://www.yourwebsite.com/your-page-url” />
Instructions: Add the canonical tag within the <head> section of your HTML to indicate the preferred version of a page.
10. 301 Redirects (htaccess)
Description: Redirect old URLs to new ones.
htaccess
Redirect 301 /old-page.html https://www.yourwebsite.com/new-page.html
Instructions: Add these lines to your .htaccess file on your server to permanently redirect old URLs to new ones.
11. Google Analytics (JavaScript)
Description: Track website traffic and user behaviour.
html
https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-X
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag(‘js’, new Date());
gtag(‘config’, ‘UA-XXXXXX-X’);
</script>
Instructions: Replace UA-XXXXXX-X with your Google Analytics tracking ID and add this code to the <head> section of your HTML.
12. Minify CSS (Python)
Description: Minify CSS for faster load times.
python
import csscompressor
css = “””
body {
font-family: Arial, sans-serif;
color: #333;
}
h1 {
font-size: 2em;
}
“””
minified_css = csscompressor.compress(css)
print(minified_css)
Instructions: Install the csscompressor library (pip install csscompressor), and run the script to minify your CSS.
13. Minify JavaScript (Python)
Description: Minify JavaScript for faster load times.
python
import jsmin
js = “””
function hello() {
console.log(‘Hello, world!’);
}
hello();
“””
minified_js = jsmin.jsmin(js)
print(minified_js)
Instructions: Install the jsmin library (pip install jsmin), and run the script to minify your JavaScript code.
14. Image Optimisation (Python with PIL)
Description: Optimise images for faster load times.
python
from PIL import Image
def optimise_image(input_path, output_path, quality=85):
with Image.open(input_path) as img:
img.save(output_path, “JPEG”, quality=quality)
optimise_image(‘input.jpg’, ‘output.jpg’)
Instructions: Install the Pillow library (pip install pillow), and run the script to optimise your images.
15. Alt Text for Images (HTML)
Description: Add alt text to images for better SEO.
html
<img src=”image.jpg” alt=”Description of the image”>
Instructions: Always include the alt attribute in your <img> tags with a descriptive text about the image.
16. Social Media Meta Tags (HTML)
Description: Add Open Graph tags for better social sharing.
html
<meta property=”og:title” content=”Your Page Title”>
<meta property=”og:description” content=”Your page description”>
<meta property=”og:image” content=”https://www.yourwebsite.com/image.jpg”>
<meta property## Ultimate Coding for SEO Cheat Sheet
### 1. Meta Tags (HTML)
**Description:** Add essential meta tags for SEO.
“`html
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<meta name=”description” content=”Your page description here”>
<meta name=”keywords” content=”keyword1, keyword2, keyword3″>
<meta name=”robots” content=”index, follow”>
<title>Your Page Title</title>
</head>
<body>
<!– Your content here –>
</body>
</html>
Instructions: Place the meta tags within the <head> section of your HTML document. Replace the placeholders with relevant content for your site
17. Read More Functionality (JavaScript)
Description: Toggle content visibility with a “Read More” button.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
.more-content { display: none; }
.read-more { color: blue; cursor: pointer; }
</style>
</head>
<body>
<p>This is a short introduction…</p>
<p class=”more-content”>Here is the rest of the content that will be hidden initially.</p>
<span class=”read-more”>Read More</span>
<script>
document.querySelector(‘.read-more’).addEventListener(‘click’, function() {
var moreContent = document.querySelector(‘.more-content’);
if (moreContent.style.display === ‘none’) {
moreContent.style.display = ‘block’;
this.textContent = ‘Read Less’;
} else {
moreContent.style.display = ‘none’;
this.textContent = ‘Read More’;
}
});
</script>
</body>
</html>
Instructions: Add the HTML structure to your page. Style the hidden content and toggle its visibility using JavaScript.
18. Accordions (JavaScript and CSS)
Description: Create collapsible accordion sections.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
.accordion { cursor: pointer; padding: 10px; border: 1px solid #ccc; margin-top: 5px; }
.panel { display: none; padding: 0 10px; border: 1px solid #ccc; border-top: none; }
</style>
</head>
<body>
<div class=”accordion”>Section 1</div>
<div class=”panel”>
<p>Content for section 1…</p>
</div>
<div class=”accordion”>Section 2</div>
<div class=”panel”>
<p>Content for section 2…</p>
</div>
<script>
var accordions = document.getElementsByClassName(‘accordion’);
for (var i = 0; i < accordions.length; i++) {
accordions[i].addEventListener(‘click’, function() {
this.classList.toggle(‘active’);
var panel = this.nextElementSibling;
if (panel.style.display === ‘block’) {
panel.style.display = ‘none’;
} else {
panel.style.display = ‘block’;
}
});
}
</script>
</body>
</html>
Instructions: Add the accordion structure and style it with CSS. Use JavaScript to toggle the visibility of the panels.
19. Footer Links (HTML and CSS)
Description: Organise footer links for better navigation.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
footer { background: #333; color: #fff; padding: 20px 0; }
.footer-links { display: flex; justify-content: space-around; }
.footer-links a { color: #fff; text-decoration: none; margin: 0 10px; }
.footer-links a:hover { text-decoration: underline; }
</style>
</head>
<body>
<footer>
<div class=”footer-links”>
<a href=”/about-us”>About Us</a>
<a href=”/services”>Services</a>
<a href=”/contact”>Contact</a>
<a href=”/privacy-policy”>Privacy Policy</a>
</div>
</footer>
</body>
</html>
Instructions: Add the footer section to your HTML and style it with CSS to ensure good visibility and usability.
20. Sticky Navigation Bar (HTML and CSS)
Description: Keep the navigation bar fixed at the top of the page.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
body { margin: 0; font-family: Arial, sans-serif; }
.navbar { position: -webkit-sticky; position: sticky; top: 0; background: #333; padding: 10px; color: white; }
.navbar a { color: white; text-decoration: none; padding: 8px 16px; display: inline-block; }
.navbar a:hover { background: #575757; }
</style>
</head>
<body>
<div class=”navbar”>
<a href=”#home”>Home</a>
<a href=”#services”>Services</a>
<a href=”#contact”>Contact</a>
<a href=”#about”>About</a>
</div>
<div style=”padding:15px 15px 2500px”>
<h2>Scroll Down</h2>
<p>Scroll down to see the sticky effect.</p>
</div>
</body>
</html>
Instructions: Add the navigation bar to your HTML and use CSS to make it sticky. The position: sticky property keeps it at the top of the viewport when scrolling.
21. Modal Pop-up (HTML, CSS, and JavaScript)
Description: Create a modal pop-up for additional content.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
body { font-family: Arial, sans-serif; }
.modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4); }
.modal-content { background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; }
.close { color: #aaa; float: right; font-size: 28px; font-weight: bold; }
.close:hover, .close:focus { color: black; text-decoration: none; cursor: pointer; }
</style>
</head>
<body>
<h2>Modal Example</h2>
<button id=”openModal”>Open Modal</button>
<div id=”myModal” class=”modal”>
<div class=”modal-content”>
<span class=”close”>×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<script>
var modal = document.getElementById(‘myModal’);
var btn = document.getElementById(‘openModal’);
var span = document.getElementsByClassName(‘close’)[0];
btn.onclick = function() {
modal.style.display = ‘block’;
}
span.onclick = function() {
modal.style.display = ‘none’;
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = ‘none’;
}
}
</script>
</body>
</html>
Instructions: Add the modal structure to your HTML, style it with CSS, and use JavaScript to control its visibility.
22. Breadcrumb Navigation (HTML and CSS)
Description: Enhance user navigation with breadcrumbs.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
.breadcrumb { list-style: none; display: flex; }
.breadcrumb li { margin-right: 5px; }
.breadcrumb li a { text-decoration: none; color: #0275d8; }
.breadcrumb li a:hover { text-decoration: underline; }
.breadcrumb li::after { content: ‘>’; margin-left: 5px; }
.breadcrumb li:last-child::after { content: ”; }
</style>
</head>
<body>
<ul class=”breadcrumb”>
<li><a href=”/”>Home</a></li>
<li><a href=”/category”>Category</a></li>
<li>Current Page</li>
</ul>
</body>
</html>
Instructions: Add the breadcrumb structure to your HTML and style it with CSS for clear navigation.
23. Back to Top Button (HTML, CSS, and JavaScript)
Description: Create a button that scrolls the user back to the top of the page.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
#topBtn { display: none; position: fixed; bottom: 20px; right: 30px; z-index: 99; border: none; outline: none; background-color: red; color: white; cursor: pointer; padding: 15px; border-radius: 10px; }
#topBtn:hover { background-color: #555; }
</style>
</head>
<body>
<button onclick=”topFunction()” id=”topBtn” title=”Go to top”>Top</button>
<script>
var topButton = document.getElementById(‘topBtn’);
window.onscroll = function() { scrollFunction(); };
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
topButton.style.display = ‘block’;
} else {
topButton.style.display = ‘none’;
}
}
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
</script>
</body>
</html>
Instructions: Add the button to your HTML and style ite
Instructions: Add the button to your HTML and style it with CSS. Use JavaScript to control its visibility and scroll behaviour.
24. Mobile-Friendly Menu (HTML, CSS, and JavaScript)
Description: Create a responsive, mobile-friendly navigation menu.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
body { font-family: Arial, sans-serif; }
.navbar { overflow: hidden; background-color: #333; }
.navbar a { float: left; display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; }
.navbar a:hover { background-color: #ddd; color: black; }
.navbar a.active { background-color: #4CAF50; color: white; }
.icon { display: none; }
@media screen and (max-width: 600px) {
.navbar a { float: none; display: block; text-align: left; }
.icon { float: right; display: block; }
}
</style>
</head>
<body>
<div class=”navbar” id=”myNavbar”>
<a href=”#home” class=”active”>Home</a>
<a href=”#services”>Services</a>
<a href=”#contact”>Contact</a>
<a href=”#about”>About</a>
<a href=”javascript:void(0);” class=”icon” onclick=”myFunction()”>☰</a>
</div>
<script>
function myFunction() {
var x = document.getElementById(“myNavbar”);
if (x.className === “navbar”) {
x.className += ” responsive”;
} else {
x.className = “navbar”;
}
}
</script>
</body>
</html>
Instructions: Add the navigation menu to your HTML and style it with CSS. Use JavaScript to toggle the menu’s visibility on smaller screens.
25. Dynamic Year in Footer (JavaScript)
Description: Automatically update the year in the footer.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
</head>
<body>
<footer>
<p>© <span id=”year”></span> Your Company Name. All rights reserved.</p>
</footer>
<script>
document.getElementById(‘year’).textContent = new Date().getFullYear();
</script>
</body>
</html>
Instructions: Add the footer element to your HTML and use JavaScript to dynamically update the year.
26. Image Carousel (HTML, CSS, and JavaScript)
Description: Create a simple image carousel.
html
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
.carousel { position: relative; max-width: 100%; margin: auto; }
.slides { display: none; width: 100%; }
.prev, .next { cursor: pointer; position: absolute; top: 50%; width: auto; padding: 16px; color: white; font-weight: bold; transition: 0.6s ease; }
.prev { left: 0; }
.next { right: 0; }
</style>
</head>
<body>
<div class=”carousel”>
<img class=”slides” src=”img1.jpg” alt=”Image 1″>
<img class=”slides” src=”img2.jpg” alt=”Image 2″>
<img class=”slides” src=”img3.jpg” alt=”Image 3″>
<a class=”prev” onclick=”plusSlides(-1)”>❮</a>
<a class=”next” onclick=”plusSlides(1)”>❯</a>
</div>
<script>
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName(“slides”);
if (n > slides.length) { slideIndex = 1 }
if (n < 1) { slideIndex = slides.length }
for (i = 0; i < slides.length; i++) {
slides[i].style.display = “none”;
}
slides[slideIndex – 1].style.display = “block”;
}
</script>
</body>
</html>
Instructions: Add the carousel structure to your HTML, style it with CSS, and use JavaScript to control the image slides.
27. Form Validation (HTML, CSS, and JavaScript)
Description: Implement basic form validation.
html
Copy code
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
.error { color: red; }
</style>
</head>
<body>
<form id=”myForm”>
<label for=”name”>Name:</label>
<input type=”text” id=”name” name=”name” required>
<span class=”error” id=”nameError”></span>
<br>
<label for=”email”>Email:</label>
<input type=”email” id=”email” name=”email” required>
<span class=”error” id=”emailError”></span>
<br>
<input type=”submit” value=”Submit”>
</form>
<script>
document.getElementById(‘myForm’).addEventListener(‘submit’, function(event) {
var valid = true;
if (!document.getElementById(‘name’).value) {
document.getElementById(‘nameError’).textContent = ‘Name is required’;
valid = false;
} else {
document.getElementById(‘nameError’).textContent = ”;
}
if (!document.getElementById(’email’).value) {
document.getElementById(’emailError’).textContent = ‘Email is required’;
valid = false;
} else {
document.getElementById(’emailError’).textContent = ”;
}
if (!valid) {
event.preventDefault();
}
});
</script>
</body>
</html>
Instructions: Add the form structure to your HTML, style error messages with CSS, and use JavaScript to validate form inputs before submission.
28. Google Maps Integration (HTML and JavaScript)
Description: Embed a Google Map on your website.
html
Copy code
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
#map { height: 400px; width: 100%; }
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id=”map”></div>
<script>
function initMap() {
var location = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById(‘map’), {
zoom: 4,
center: location
});
var marker = new google.maps.Marker({
position: location,
map: map
});
}
</script>
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap
</body>
</html>
Instructions: Add the map container to your HTML and style it with CSS. Use the Google Maps API to initialise and display the map. Replace YOUR_API_KEY with your actual API key.
29. Sticky Footer (HTML and CSS)
Description: Create a footer that sticks to the bottom of the page.
html
Copy code
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
html, body { height: 100%; margin: 0; }
.wrapper { display: flex; flex-direction: column; min-height: 100vh; }
.content { flex: 1; }
footer { background: #333; color: white; padding: 10px; text-align: center; }
</style>
</head>
<body>
<div class=”wrapper”>
<div class=”content”>
<!– Your main content here –>
</div>
<footer>
© 2023 Your Company Name. All rights reserved.
</footer>
</div>
</body>
</html>
Instructions: Wrap your main content and footer in a flex container to ensure the footer sticks to the bottom of the page when there’s not enough content to fill the screen.
30. Hover Effects for Links (CSS)
Description: Add hover effects to improve link visibility.
html
Copy code
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
a { text-decoration: none; color: #333; }
a:hover { text-decoration: underline; color: #007BFF; }
</style>
</head>
<body>
<a href=”#link”>Hover over this link</a>
</body>
</html>
Instructions: Style links with CSS to add visual feedback when users hover over them.
32. Automatic Image Alt Text (Python)
Description: Add alt text to images that are missing it.
python
from bs4 import BeautifulSoup
html = “””
<!DOCTYPE html>
<html lang=”en”>
<head></head>
<body>
<img src=”image1.jpg”>
<img src=”image2.jpg” alt=”Already has alt text”>
</body>
</html>
“””
soup = BeautifulSoup(html, ‘html.parser’)
images = soup.find_all(‘img’)
for img in images:
if not img.has_attr(‘alt’):
img[‘alt’] = ‘Description for ‘ + img[‘src’]
print(soup.prettify())
Instructions: Use BeautifulSoup to parse the HTML and add alt text to images that are missing it. Install BeautifulSoup (pip install beautifulsoup4).
33. Check for Broken Links (Python)
Description: Find and report broken links on your website.
python
import requests
from bs4 import BeautifulSoup
url = ‘https://www.yourwebsite.com’
response = requests.get(url)
soup = BeautifulSoup(response.text, ‘html.parser’)
links = soup.find_all(‘a’)
broken_links = []
for link in links:
href = link.get(‘href’)
if href and href.startswith(‘http’):
try:
r = requests.head(href)
if r.status_code >= 400:
broken_links.append(href)
except requests.exceptions.RequestException as e:
broken_links.append(href)
print(‘Broken links:’, broken_links)
Instructions: Use Requests and BeautifulSoup to find and check all links on your website for broken ones. Install the required libraries (pip install requests beautifulsoup4).
34. Generate Meta Descriptions (Python)
Description: Automatically generate meta descriptions for pages.
python
from bs4 import BeautifulSoup
html = “””
<!DOCTYPE html>
<html lang=”en”>
<head></head>
<body>
<h1>Page Title</h1>
<p>This is the content of the page. It provides detailed information about the topic.</p>
</body>
</html>
“””
soup = BeautifulSoup(html, ‘html.parser’)
meta_description = soup.find(‘meta’, attrs={‘name’: ‘description’})
if not meta_description:
content = soup.body.get_text()[:150] + ‘…’
new_meta = soup.new_tag(‘meta’, name=’description’, content=content)
soup.head.append(new_meta)
print(soup.prettify())
Instructions: Parse the HTML, extract the first 150 characters of text, and create a meta description if it doesn’t already exist.
35. Create Sitemap (Python)
Description: Generate a simple XML sitemap.
python
import os
urls = [
‘https://www.yourwebsite.com/’,
‘https://www.yourwebsite.com/about/’,
‘https://www.yourwebsite.com/contact/’
]
with open(‘sitemap.xml’, ‘w’) as f:
f.write(‘<?xml version=”1.0″ encoding=”UTF-8″?>\n’)
f.write(‘<urlset xmlns=”http://www.sitemaps.org/schemas/sitemap/0.9″>\n’)
for url in urls:
f.write(‘ <url>\n’)
f.write(f’ <loc>{url}</loc>\n’)
f.write(‘ <priority>0.8</priority>\n’)
f.write(‘ </url>\n’)
f.write(‘</urlset>\n’)
Instructions: Create a list of URLs and write them to a sitemap.xml file in XML format.
36. Automate Google Search Console URL Inspection (Python)
Description: Automate URL inspection using Google Search Console API.
python
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = [‘https://www.googleapis.com/auth/webmasters’]
SERVICE_ACCOUNT_FILE = ‘path/to/your/service-account-file.json’
URL_TO_INSPECT = ‘https://www.yourwebsite.com/page-to-inspect’
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build(‘searchconsole’, ‘v1’, credentials=credentials)
request = {
‘inspectionUrl’: URL_TO_INSPECT,
‘languageCode’: ‘en’
}
response = service.urlInspection().index().inspect(body=request).execute()
print(response)
Instructions: Authenticate using a service account file and make a URL inspection request to the Google Search Console API. Replace placeholders with your actual data.
37. SEO Audit Report (Python)
Description: Generate a basic SEO audit report for a website.
python
import requests
from bs4 import BeautifulSoup
url = ‘https://www.yourwebsite.com’
response = requests.get(url)
soup = BeautifulSoup(response.text, ‘html.parser’)
title = soup.title.string if soup.title else ‘No title found’
meta_description = soup.find(‘meta’, attrs={‘name’: ‘description’})
meta_description = meta_description[‘content’] if meta_description else ‘No meta description found’
h1_tags = [h1.string for h1 in soup.find_all(‘h1’)]
print(f’Title: {title}’)
print(f’Meta Description: {meta_description}’)
print(f’H1 Tags: {h1_tags}’)
Instructions: Fetch a webpage, parse the HTML, and extract key SEO elements such as the title, meta description, and H1 tags. Install the required libraries (pip install requests beautifulsoup4).
38. Automated Redirects (Python with Flask)
Description: Automatically handle 301 redirects for moved pages.
python
from flask import Flask, redirect
app = Flask(__name__)
redirects = {
‘/old-page’: ‘/new-page’,
‘/another-old-page’: ‘/another-new-page’
}
@app.route(‘/<path:path>’)
def handle_redirects(path):
if f’/{path}’ in redirects:
return redirect(redirects[f’/{path}’], 301)
else:
return ‘Page not found’, 404
if __name__ == ‘__main__’:
app.run(debug=True)
Instructions: Define a dictionary of old and new URLs. Create a Flask route that handles redirects based on the dictionary entries.
39. Monitor Website Changes (Python)
Description: Monitor changes on a webpage and alert if changes occur.
python
import requests
from bs4 import BeautifulSoup
import hashlib
url = ‘https://www.yourwebsite.com’
response = requests.get(url)
soup = BeautifulSoup(response.text, ‘html.parser’)
current_hash = hashlib.md5(soup.prettify().encode(‘utf-8’)).hexdigest()
# Load the previous hash from a file
try:
with open(‘hash.txt’, ‘r’) as file:
previous_hash = file.read()
except FileNotFoundError:
previous_hash = ”
if current_hash != previous_hash:
print(‘Webpage has changed!’)
with open(‘hash.txt’, ‘w’) as file:
file.write(current_hash)
else:
print(‘No changes detected.’)
Instructions: Fetch the webpage and create a hash of its content. Compare the hash with a stored value to detect changes. Install the required libraries (pip install requests beautifulsoup4).
40. Automated Keyword Position Tracking (Python)
Description: Track keyword positions in search results.
python
import requests
from bs4 import BeautifulSoup
keywords = [‘keyword1’, ‘keyword2’]
site_url = ‘yourwebsite.com’
for keyword in keywords:
response = requests.get(f’https://www.google.com/search?q={keyword}’)
soup = BeautifulSoup(response.text, ‘html.parser’)
results = soup.find_all(‘div’, class_=’g’)
for index, result in enumerate(results, start=1):
link = result.find(‘a’)[‘href’]
if site_url in link:
print(f’Keyword: {keyword}, Position: {index}’)
break
Instructions: Query Google for each keyword and parse the search results to find the position of your site. Note: Scraping Google is against their terms of service; consider using an API like SerpApi. Install the required libraries (pip install requests beautifulsoup4).
41. Detect Missing H1 Tags (Python)
Description: Check if pages are missing H1 tags.
python
import requests
from bs4 import BeautifulSoup
urls = [
‘https://www.yourwebsite.com/page1’,
‘https://www.yourwebsite.com/page2’
]
for url in urls:
response = requests.get(url)
soup = BeautifulSoup(response.text, ‘html.parser’)
h1 = soup.find(‘h1’)
if not h1:
print(f’No H1 tag found on {url}’)
else:
print(f’H1 tag found on {url}’)
Instructions: Fetch each URL and parse the HTML to check for the presence of H1 tags. Install the required libraries (pip install requests beautifulsoup4).
Subscribe to get access
Read more of this content when you subscribe today.
Subscriber Content
Add content here that will only be visible to your subscribers.