Blog Details

Linux 作業系統 cutexyz > Blog > 未分類 > Python 統計用

Python 統計用

需要安裝
pip install requests beautifulsoup4

code

from collections import Counter
import re
import requests
from bs45 import BeautifulSoup  # 如果匯入錯誤請確保用 pip install beautifulsoup4


def main():
  # 設定請求次數變數
  TOTAL_REQUESTS = 130
  # 請將此處替換為你的目標 URL
  URL = "https://example.com/your-target-url"

  numbers_collected = []

  print(f"開始進行 {TOTAL_REQUESTS} 次 HTTP Request...")

  for i in range(TOTAL_REQUESTS):
    # 顯示簡單的進度條
    print(f"進度: {i + 1}/{TOTAL_REQUESTS}", end="\r")

    try:
      response = requests.get(URL, timeout=10)
      if response.status_code == 200:
        # 解析 HTML
        soup = BeautifulSoup(response.text, "html.parser")
        h1_tag = soup.find("h1")

        if h1_tag:
          # 取得 h1 內的文字並利用正規表達式抓出數字
          h1_text = h1_tag.get_text(strip=True)
          match = re.search(r"\d+", h1_text)
          if match:
            number = int(match.group())
            numbers_collected.append(number)
      else:
        print(f"\n第 {i + 1} 次請求失敗,狀態碼: {response.status_code}")
    except Exception as e:
      print(f"\n第 {i + 1} 次請求發生錯誤: {e}")

  print("\n\n" + "=" * 30)
  print("         統計結果")
  print("=" * 30)

  if numbers_collected:
    # 統計每個數字出現的次數
    stats = Counter(numbers_collected)

    print(f"總成功獲取次數:{len(numbers_collected)} / {TOTAL_REQUESTS}")
    print("\n各數字出現統計:")
    # 依照數字大小順序排序輸出
    for num, count in sorted(stats.items()):
      print(f"數字 {num}:出現 {count} 次")
  else:
    print("未成功獲取任何有效數字。")


if __name__ == "__main__":
  main()

Leave A Comment

All fields marked with an asterisk (*) are required