Python has become a powerful tool for digital marketers looking to automate repetitive tasks and gain valuable insights through data analysis.
Knowing essential Python scripts can help you streamline processes, from data extraction to automated reporting.
This blog covers five must-know Python scripts that can elevate your digital marketing workflow.
Python allows you to extract data from Google Analytics using the Google Analytics API. This script can pull metrics like sessions, bounce rate, and conversion rates, giving you the data needed to track performance.
Example Code:
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'path/to/your-service-account-key.json'
VIEW_ID = 'ga:YOUR_VIEW_ID'
credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES)
analytics = build('analytics', 'v3', credentials=credentials)
response = analytics.data().ga().get(
ids=VIEW_ID,
start_date='7daysAgo',
end_date='today',
metrics='ga:sessions,ga:pageviews,ga:goalCompletionsAll'
).execute()
print(response)
Using Python libraries like Tweepy (for Twitter) or Facebook’s Graph API, you can track engagement metrics, analyze hashtags, and understand audience sentiment, helping you optimize social strategies.
Example Use Case: Analyze the engagement rate for a specific hashtag over the last month and identify trending topics among your audience.
Example Code:
import tweepy
from textblob import TextBlob
from datetime import datetime, timedelta
import pandas as pd
API_KEY = 'your_api_key'
API_SECRET_KEY = 'your_api_secret_key'
ACCESS_TOKEN = 'your_access_token'
ACCESS_TOKEN_SECRET = 'your_access_token_secret'
auth = tweepy.OAuth1UserHandler(API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
def analyze_hashtag_engagement(hashtag, days=30):
end_date = datetime.now()
start_date = end_date - timedelta(days=days)
tweets_data = []
for tweet in tweepy.Cursor(api.search_tweets, q=f"#{hashtag}", lang="en", since=start_date.strftime('%Y-%m-%d')).items(200):
tweet_data = {
"text": tweet.text,
"likes": tweet.favorite_count,
"retweets": tweet.retweet_count,
"date": tweet.created_at,
"sentiment": TextBlob(tweet.text).sentiment.polarity
}
tweets_data.append(tweet_data)
df = pd.DataFrame(tweets_data)
avg_likes = df['likes'].mean()
avg_retweets = df['retweets'].mean()
sentiment_avg = df['sentiment'].mean()
print(f"Hashtag: #{hashtag}")
print(f"Average Likes: {avg_likes:.2f}")
print(f"Average Retweets: {avg_retweets:.2f}")
print(f"Average Sentiment: {sentiment_avg:.2f}")
return df
With Python and SMTP libraries, you can automate email reports to deliver performance summaries to stakeholders. This saves time on manually compiling and sending reports, ensuring that your team is updated on key metrics.
Example Code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from getpass import getpass
def send_email(report, sender_email, recipient_emails, smtp_server, smtp_port):
try:
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = ', '.join(recipient_emails)
msg['Subject'] = 'Weekly Performance Report'
msg.attach(MIMEText(report, 'plain'))
password = getpass(f"Enter the password for {sender_email}: ")
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, recipient_emails, msg.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"An error occurred: {e}")
finally:
server.quit()
Python’s BeautifulSoup and Selenium libraries enable web scraping, which can be useful for competitive analysis. For example, you can extract competitor prices, reviews, and other data points to monitor market trends.
Example: Scrape product prices from competitor websites and analyze changes over time.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import time
def scrape_product_prices(url):
service = Service("path/to/chromedriver")
options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(service=service, options=options)
try:
driver.get(url)
time.sleep(3)
page_source = driver.page_source
soup = BeautifulSoup(page_source, 'html.parser')
products = []
for product in soup.find_all('div', class_='product-class'):
name = product.find('h2', class_='product-name-class').text.strip()
price = product.find('span', class_='price-class').text.strip()
products.append({'name': name, 'price': price})
return products
except Exception as e:
print(f"An error occurred: {e}")
return []
finally:
driver.quit()
Python’s Matplotlib and Seaborn libraries allow you to visualize marketing data, making it easier to identify patterns and trends. You can create bar charts, line graphs, and scatter plots to represent data like website traffic or ad performance.
Example: Create a line graph showing monthly traffic growth over the past year, helping you identify peak performance periods.
Example Code:
import matplotlib.pyplot as plt
import pandas as pd
data = {
"Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
"Traffic": [1200, 1500, 1700, 1800, 2400, 2500, 2200, 2100, 2600, 2800, 3000, 3500]
}
df = pd.DataFrame(data)
def plot_monthly_traffic(dataframe):
plt.figure(figsize=(10, 6))
plt.plot(dataframe['Month'], dataframe['Traffic'], marker='o')
plt.title('Monthly Traffic Growth Over the Past Year', fontsize=14)
plt.xlabel('Month', fontsize=12)
plt.ylabel('Traffic', fontsize=12)
plt.grid(True)
plt.tight_layout()
plt.show()
Mastering these Python scripts can enhance your digital marketing efforts, making tasks like data extraction, analysis, and reporting more efficient. Embrace Python in 2024 to optimize your marketing workflow, gain valuable insights, and stay ahead of the competition.
Check out my portfolio for examples of Python-based solutions I’ve developed to streamline marketing processes, or connect with me to know how I can help you based on your requirement.