Python 提供了便捷的工具來測量網站載入時間,透過 urllibtime 模組,可以精確記錄網頁載入的耗時。此外,Flask 框架結合 SQLAlchemy ORM,能快速打造功能完善的 Web 應用程式,例如 Todo App,實作任務的新增、刪除和更新。文章也涵蓋了使用 Snscrape 抓取 Twitter 標籤推文、開發打字速度測試程式以及 Instagram 追蹤者管理工具的實用技巧,提供程式碼範例和流程圖說明。

使用方法

  1. 在命令提示符中輸入以下命令:
python time_to_load_website.py
  1. 系統會要求您輸入URL,請輸入您想要測試的網站URL,然後按Enter鍵。

範例使用

以下是範例使用的截圖:

範例截圖

  flowchart TD
    A[使用者輸入URL] --> B[系統計算載入時間]
    B --> C[系統顯示結果]

圖表翻譯

此流程圖描述了使用者輸入URL、系統計算載入時間、以及系統顯示結果的過程。

程式碼

from urllib.request import urlopen
import time

def get_load_time(url):
    """
    這個函式計算網站載入的時間。
    
    Args:
        url (string): 網站的URL。
    
    Returns:
        time_to_load (float): 網站載入的時間(秒)。
    """
    if ("https" or "http") in url:  # 檢查URL是否包含協定
        open_this_url = urlopen(url)  # 開啟URL
        start_time = time.time()  # 記錄開始時間
        open_this_url.read()  # 讀取網站內容
        end_time = time.time()  # 記錄結束時間
        open_this_url.close()  # 關閉URL連結
        
        time_to_load = end_time - start_time  # 計算載入時間
        
        return time_to_load

if __name__ == '__main__':
    url = input("請輸入您想要測試的網站URL:")
    print(f"\n載入 {url} 的時間為 {get_load_time(url):.2} 秒。")

內容解密

此程式碼使用urlopen函式開啟指定的URL,然後使用time模組記錄開始和結束時間,最後計算載入時間並傳回結果。

Todo App 使用 Flask

以下是使用Flask建立Todo App的範例:

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///todo.db"
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    completed = db.Column(db.Boolean, default=False)

    def __repr__(self):
        return f"Todo({self.title}, {self.completed})"

@app.route("/todos", methods=["GET", "POST"])
def todos():
    if request.method == "POST":
        new_todo = Todo(title=request.json["title"], completed=False)
        db.session.add(new_todo)
        db.session.commit()
        return jsonify({"message": "Todo created successfully!"})
    else:
        todos = Todo.query.all()
        output = []
        for todo in todos:
            todo_data = {"id": todo.id, "title": todo.title, "completed": todo.completed}
            output.append(todo_data)
        return jsonify({"todos": output})

if __name__ == "__main__":
    app.run(debug=True)

圖表翻譯

此Todo App使用Flask框架建立,包含新增和查詢Todo專案的功能。以下是流程圖:

  flowchart TD
    A[使用者傳送POST請求] --> B[系統建立新Todo]
    B --> C[系統儲存Todo]
    C --> D[系統傳回成功訊息]
    E[使用者傳送GET請求] --> F[系統查詢所有Todo]
    F --> G[系統傳回Todo列表]

此流程圖描述了使用者傳送POST請求建立新Todo、系統儲存Todo、系統傳回成功訊息、使用者傳送GET請求查詢所有Todo、以及系統傳回Todo列表的過程。

工作清單應用程式開發

概述

工作清單應用程式是一種簡單的Web應用程式,允許使用者新增、刪除和更新任務。以下是工作清單應用程式的詳細介紹。

功能

工作清單應用程式具有以下功能:

  1. 新增任務:使用者可以新增新的任務到工作清單中。
  2. 刪除任務:使用者可以刪除工作清單中的任務。
  3. 更新任務:使用者可以更新工作清單中的任務。

執行應用程式

要執行工作清單應用程式,請按照以下步驟:

  • 建立虛擬環境:建立一個虛擬環境,以隔離應用程式的依賴項。
  • 安裝依賴項:安裝應用程式所需的依賴項,包括Flask和Flask-SQLAlchemy。
pip install -r requirements.txt
  • 執行應用程式:執行應用程式的主程式。
py app.py

依賴項

工作清單應用程式需要以下依賴項:

  • Flask==1.1.2
  • Flask-SQLAlchemy==2.4.4

程式碼

以下是工作清單應用程式的程式碼:

from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///todo.db"
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    task = db.Column(db.String(100), nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
        return "<Task %r>" % self.id

@app.route("/", methods=["POST", "GET"])
def index():
    if request.method == "POST":
        task_content = request.form["task"]
        new_task = Todo(task=task_content)
        db.session.add(new_task)
        db.session.commit()
        return redirect(url_for("index"))
    else:
        tasks = Todo.query.all()
        return render_template("index.html", tasks=tasks)

if __name__ == "__main__":
    app.run(debug=True)

內容解密:

上述程式碼定義了一個簡單的工作清單應用程式,使用Flask和Flask-SQLAlchemy框架。應用程式具有新增、刪除和更新任務的功能。程式碼包括以下部分:

  • 資料函式庫模型:定義了一個Todo模型,代表工作清單中的任務。
  • 路由:定義了一個路由,處理新增任務的請求。
  • 新增任務:新增任務到工作清單中。
  • 刪除任務:刪除工作清單中的任務。
  • 更新任務:更新工作清單中的任務。

圖表翻譯:

以下是工作清單應用程式的流程圖:

  flowchart TD
    A[使用者請求] --> B[新增任務]
    B --> C[儲存任務]
    C --> D[重導向]
    D --> E[顯示工作清單]
    E --> F[使用者請求]
    F --> G[刪除任務]
    G --> H[刪除任務]
    H --> I[重導向]
    I --> E

上述流程圖顯示了工作清單應用程式的流程,包括新增任務、儲存任務、重導向、顯示工作清單、刪除任務等步驟。

使用 Flask 開發 Todo List 應用程式

應用程式架構

本應用程式使用 Flask 框架開發,包括以下路由:

  • /: Todo List 首頁,顯示所有任務
  • /delete/<int:id>: 刪除指定 ID 的任務
  • /update/<int:id>: 更新指定 ID 的任務

資料函式庫設定

使用 Flask-SQLAlchemy 進行資料函式庫操作,定義 Todo 模型如下:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(100), nullable=False)
    pub_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    def __repr__(self):
        return f'Todo({self.id}, {self.content})'

首頁路由

首頁路由負責顯示所有任務,並提供新增任務的功能:

@app.route("/", methods=["POST", "GET"])
def index():
    if request.method == "POST":
        task_content = request.form["content"]
        new_task = Todo(content=task_content)
        try:
            db.session.add(new_task)
            db.session.commit()
            return redirect("/")
        except:
            return "There is an issue"
    else:
        tasks = Todo.query.order_by(Todo.pub_date).all()
        return render_template("index.html", tasks=tasks)

刪除路由

刪除路由負責刪除指定 ID 的任務:

@app.route("/delete/<int:id>")
def delete(id):
    task = Todo.query.get_or_404(id)
    try:
        db.session.delete(task)
        db.session.commit()
        return redirect("/")
    except:
        return "This is an Problem while deleting"

更新路由

更新路由負責更新指定 ID 的任務:

@app.route("/update/<int:id>", methods=["POST", "GET"])
def update(id):
    task = Todo.query.get_or_404(id)
    if request.method == "POST":
        task.content = request.form["content"]
        try:
            db.session.commit()
            return redirect("/")
        except:
            return "There is an issue"
    else:
        tasks = Todo.query.order_by(Todo.pub_date).all()
        return render_template("index.html", update_task=task, tasks=tasks)

啟動應用程式

啟動應用程式使用 app.run() 函式:

if __name__ == "__main__":
    app.run(debug=True)

內容解密:

以上程式碼使用 Flask 框架開發 Todo List 應用程式,包括首頁路由、刪除路由和更新路由。使用 Flask-SQLAlchemy 進行資料函式庫操作,定義 Todo 模型儲存任務資料。每個路由都有其特定的功能,例如新增任務、刪除任務和更新任務。程式碼使用 try-except 區塊處理資料函式庫操作的異常情況,確保應用程式的穩定性。

圖表翻譯:

以下是 Todo List 應用程式的流程圖:

  flowchart TD
    A[首頁] --> B[新增任務]
    B --> C[儲存任務]
    C --> D[刪除任務]
    D --> E[更新任務]
    E --> F[儲存更新]
    F --> A

此圖表展示了 Todo List 應用程式的主要流程,包括新增任務、刪除任務和更新任務。每個步驟都對應到程式碼中的特定路由和功能。

使用Snscrape進行Twitter標籤抓取

無需Twitter API,Snscrape是一個Python函式庫,能夠抓取Twitter上的推文。以下是使用Snscrape抓取特定標籤的推文,並儲存在資料函式庫中的過程。

Snscrape的優點

  • 不需要Twitter API金鑰即可抓取推文
  • 可以抓取特定標籤的推文
  • 可以儲存抓取的推文在資料函式庫中

抓取推文的過程

  1. 安裝Snscrape和其他所需的函式庫:pip install -r requirements.txt
  2. 執行抓取推文的指令碼:python fetch_hashtags.py
  3. 抓取的推文將被儲存在資料函式庫中
  4. 執行顯示推文的指令碼:python display_hashtags.py
  5. 可以檢視儲存在資料函式庫中的推文資訊

需要的函式庫

  • beautifulsoup4
  • certifi
  • chardet
  • idna

抓取推文的指令碼

import snscrape.modules.twitter as sntwitter
import sqlite3

# 連線資料函式庫
conn = sqlite3.connect('tweets.db')
cursor = conn.cursor()

# 建立表
cursor.execute('''
    CREATE TABLE IF NOT EXISTS tweets
    (hashtag TEXT, content TEXT, user_id TEXT, url TEXT)
''')

# 抓取推文
for tweet in sntwitter.TwitterHashtagScraper('python').get_items():
    # 儲存推文在資料函式庫中
    cursor.execute('''
        INSERT INTO tweets (hashtag, content, user_id, url)
        VALUES (?, ?, ?, ?)
    ''', (tweet.hashtag, tweet.content, tweet.user_id, tweet.url))
    conn.commit()

# 關閉資料函式庫連線
conn.close()

顯示推文的指令碼

import sqlite3

# 連線資料函式庫
conn = sqlite3.connect('tweets.db')
cursor = conn.cursor()

# 查詢推文
cursor.execute('SELECT * FROM tweets')

# 顯示推文
for row in cursor.fetchall():
    print(f'標籤:{row[0]}')
    print(f'內容:{row[1]}')
    print(f'使用者ID:{row[2]}')
    print(f'URL:{row[3]}')
    print('------------------------')

# 關閉資料函式庫連線
conn.close()

圖表翻譯:

  flowchart TD
    A[開始] --> B[抓取推文]
    B --> C[儲存推文在資料函式庫中]
    C --> D[顯示推文]
    D --> E[結束]

圖表翻譯:此圖表展示了抓取推文的過程,從開始到結束,包括抓取推文、儲存推文在資料函式庫中和顯示推文。

打字速度測試程式

概述

以下程式碼是一個簡單的打字速度測試工具,使用Python實作。它會顯示一段文字,然後要求使用者盡快且準確地輸入這段文字。最後,它會計算使用者的打字速度並顯示結果。

程式碼

import time

# 要輸入的文字
string = "Python is an interpreted, high-level programming language"

# 計算文字中的字數
word_count = len(string.split())

# 輸出框架的邊框
border = '-+-'*10

def create_box():
    """顯示輸出框架"""
    print(border)
    print()
    print('Enter the phrase as fast as possible and with accuracy')
    print()

def typing_speed_test():
    """打字速度測試"""
    create_box()
    input("Press Enter when ready...")
    
    # 記錄開始時間
    t0 = time.time()
    
    # 讀取使用者輸入
    user_input = input()
    
    # 記錄結束時間
    t1 = time.time()
    
    # 計算使用者輸入的時間
    elapsed_time = t1 - t0
    
    # 計算使用者的打字速度(每分鐘的字數)
    speed = len(user_input.split()) / elapsed_time * 60
    
    # 顯示結果
    print(f"Your typing speed is {speed:.2f} words per minute.")

typing_speed_test()

解說

  1. 程式碼首先定義了一段文字和計算了這段文字中的字數。
  2. create_box 函式用於顯示輸出框架,包括邊框和提示文字。
  3. typing_speed_test 函式是打字速度測試的主函式。它先顯示輸出框架,然後記錄開始時間,讀取使用者輸入,記錄結束時間,計算使用者輸入的時間,最後計算使用者的打字速度並顯示結果。

執行結果

當你執行這個程式碼時,它會顯示一段文字,然後要求你盡快且準確地輸入這段文字。最後,它會計算你的打字速度並顯示結果。例如:

-+-*-+-*-+-*-+-*-+-*-+-*-+-*-

Enter the phrase as fast as possible and with accuracy

Press Enter when ready...
Python is an interpreted, high-level programming language
Your typing speed is 40.00 words per minute.

自動化Instagram追蹤者管理

背景

在社交媒體時代,管理Instagram追蹤者是一項重要的工作。然而,手動管理追蹤者可能是一項耗時的任務。因此,開發一個自動化的Instagram追蹤者管理工具是非常有必要的。

技術選型

為了實作Instagram追蹤者管理工具,我們選擇使用Python作為開發語言。Python是一種高階語言,具有簡潔的語法和豐富的函式庫函式,非常適合於開發自動化工具。

工具功能

以下是工具的主要功能:

  • 自動化追蹤者管理:工具可以自動化地追蹤或取消追蹤使用者。
  • 追蹤者分析:工具可以分析使用者的追蹤者資料,包括追蹤者數量、追蹤者增長率等。
  • 追蹤者篩選:工具可以根據使用者的需求篩選出特定的追蹤者。

實作細節

以下是工具的實作細節:

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 啟動瀏覽器
driver = webdriver.Chrome()

# 開啟Instagram登入頁面
driver.get("https://www.instagram.com/accounts/login/")

# 輸入使用者名稱和密碼
username_input = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.NAME, "username"))
)
password_input = driver.find_element(By.NAME, "password")

username_input.send_keys("your_username")
password_input.send_keys("your_password")

# 點選登入按鈕
login_button = driver.find_element(By.XPATH, "//button[@type='submit']")
login_button.click()

# 等待登入完成
time.sleep(5)

# 開啟使用者的追蹤者頁面
driver.get("https://www.instagram.com/your_username/followers/")

# 取得追蹤者列表
followers = []
while True:
    # 取得當前頁面的追蹤者
    follower_elements = driver.find_elements(By.XPATH, "//div[@class='FPmhX notranslate _0imsa ']")
    for element in follower_elements:
        follower = element.text
        followers.append(follower)

    # 點選下一頁按鈕
    next_button = driver.find_element(By.XPATH, "//button[@class=' _6c6f']")
    if next_button.text == "下一頁":
        next_button.click()
        time.sleep(2)
    else:
        break

# 關閉瀏覽器
driver.quit()

# 分析追蹤者資料
followers_count = len(followers)
print("追蹤者數量:", followers_count)

# 篩選出特定的追蹤者
specific_followers = [follower for follower in followers if follower.startswith("特定字元")]
print("特定追蹤者:", specific_followers)

Instagram追蹤者管理工具

為了方便管理Instagram的追蹤者,特別是找出那些你追蹤但沒有追蹤回來的使用者,我們可以使用一款簡單的工具。這款工具的名稱為bb8,它可以幫助你輕鬆地找出這些使用者。

從商業價值與使用者經驗角度來看,以上提供的程式碼範例涵蓋了網站載入速度測試、待辦事項應用程式、Twitter主題標籤抓取、打字速度測試,以及Instagram追蹤者管理等多種實用功能。這些程式碼片段雖簡潔,但功能明確,展現了Python在自動化任務、資料處理和網頁應用開發方面的優勢。然而,程式碼本身的健壯性和安全性仍有提升空間,例如網站載入測試程式缺乏對網路錯誤的處理,Instagram追蹤者管理工具則直接使用帳號密碼,存在安全風險。

考量到程式碼的教學用途,這些範例提供了一個良好的學習起點。透過這些程式碼,初學者可以快速掌握Python的基本語法和常用函式庫的使用方法,並進一步學習如何開發更複雜的應用程式。同時,程式碼中的一些設計思路,例如使用流程圖和「內容解密」部分,有助於提升程式碼的可讀性和理解度。

展望未來,這些程式碼片段可以進一步最佳化和擴充套件。例如,可以加入更完善的錯誤處理機制、使用更安全的認證方式、以及提供更豐富的功能。此外,可以結合更先進的技術,例如機器學習和自然語言處理,開發更智慧化的應用程式。隨著社群平臺的發展和使用者需求的變化,自動化工具和資料分析的需求將持續增長,Python及其相關生態系統也將扮演更重要的角色。玄貓認為,持續學習和精程式式設計技能,將有助於開發者更好地應對未來的挑戰,並創造更大的價值。