YouTube'da Beğendiğin Videoları Excel'e Kaydetmek

  • Konuyu açan Konuyu açan 05egecany05
  • Açılış Tarihi Açılış Tarihi
  • Yanıt Yanıt 1
  • Gösterim Gösterim 45

05egecany05

Üye
Üye
Mesaj
9
Beğeni
1
Puan
50
Ticaret Puanı
0
1786388117910.webp


Tampermonkey:
Genişlet Daralt Kopyala
// ==UserScript==
// @name         YouTube Like → Excel
// @namespace    http://tampermonkey.net/
// @version      4.0
// @description  YouTube video Like tıklamasını Excel'e kaydeder.
// @author       You
// @match        https://www.youtube.com/*
// @grant        GM_xmlhttpRequest
// @connect      127.0.0.1
// @connect      localhost
// @run-at       document-start
// ==/UserScript==

(function () {
    'use strict';

    const API_URL = 'http://127.0.0.1:5000/kaydet';

    console.log('[YT Excel] Script aktif!');


    function veriyiGonder(title, url) {

        console.log('[YT Excel] Python\'a gönderiliyor...');
        console.log('[YT Excel] Başlık:', title);
        console.log('[YT Excel] URL:', url);

        GM_xmlhttpRequest({
            method: 'POST',
            url: API_URL,

            headers: {
                'Content-Type': 'application/json'
            },

            data: JSON.stringify({
                title: title,
                url: url
            }),

            onload: function (response) {

                console.log(
                    '[YT Excel] Python cevap:',
                    response.status,
                    response.responseText
                );

                if (response.status >= 200 && response.status < 300) {

                    console.log(
                        '%c[YT Excel] KAYDEDILDI!',
                        'color:#00ff00;font-weight:bold;background:#000;padding:4px;'
                    );

                } else {

                    console.error(
                        '[YT Excel] Python hata verdi:',
                        response.status
                    );

                }
            },

            onerror: function (error) {

                console.error(
                    '[YT Excel] Python bağlantı hatası:',
                    error
                );

            }
        });
    }


    document.addEventListener('click', function (event) {

        const button = event.target.closest(
            '#top-level-buttons-computed segmented-like-dislike-button-view-model button'
        );

        if (!button) {
            return;
        }


        const label = (
            button.getAttribute('aria-label') || ''
        ).toLowerCase();


        /*
         * Sadece video Like.
         */
        if (!label.includes('videoyu beğen')) {
            return;
        }


        /*
         * Unlike / beğeniyi kaldırma ise kayıt yapma.
         */
        if (
            label.includes('beğenmekten vazgeç') ||
            label.includes('beğeniyi kaldır') ||
            label.includes('unlike')
        ) {
            console.log(
                '[YT Excel] Unlike - kayıt yapılmadı.'
            );

            return;
        }


        const titleElement =
            document.querySelector(
                '#title h1'
            ) ||
            document.querySelector(
                'h1.ytd-watch-metadata'
            ) ||
            document.querySelector(
                'h1'
            );


        const title =
            titleElement?.textContent?.trim() ||
            document.title
                .replace(' - YouTube', '')
                .trim();


        /*
         * Gerçek video URL'si.
         */
        const url = window.location.href;


        console.log(
            '%c[YT Excel] VIDEO LIKE YAKALANDI!',
            'color:#00ff00;font-weight:bold;background:#000;padding:4px;'
        );

        console.log(
            '[YT Excel] Başlık:',
            title
        );

        console.log(
            '[YT Excel] Gerçek URL:',
            url
        );


        veriyiGonder(title, url);

    }, true);

})();

Python:
Genişlet Daralt Kopyala
import os
from datetime import datetime
from flask import Flask, request, jsonify
from openpyxl import load_workbook, Workbook
from openpyxl.styles import Font, Alignment
from openpyxl.utils import get_column_letter

app = Flask(__name__)

# Masaüstündeki Excel dosyasının yolu
DESKTOP_PATH = os.path.join(os.path.expanduser("~"), "Desktop")
EXCEL_FILE = os.path.join(DESKTOP_PATH, "youtube_kayitlar.xlsx")


def excel_yaz(title, url):
    # Dosya yoksa oluştur, varsa aç
    if not os.path.exists(EXCEL_FILE):
        wb = Workbook()
        ws = wb.active
        ws.title = "Videolar"

        # Başlıklar
        ws.append(["Video Başlığı", "Video URL", "Tarih", "Saat"])

        # Başlık biçimi
        for cell in ws[1]:
            cell.font = Font(bold=True)
            cell.alignment = Alignment(horizontal="center")

        # İlk satırı sabitle
        ws.freeze_panes = "A2"

        # Filtre
        ws.auto_filter.ref = "A1:D1"

    else:
        wb = load_workbook(EXCEL_FILE)
        ws = wb.active

        # Eski dosya sadece 2 kolonluysa yeni kolonları ekle
        headers = [ws.cell(1, col).value for col in range(1, 5)]

        if headers[0] != "Video Başlığı":
            ws.cell(1, 1).value = "Video Başlığı"

        if headers[1] != "Video URL":
            ws.cell(1, 2).value = "Video URL"

        if headers[2] is None:
            ws.cell(1, 3).value = "Tarih"

        if headers[3] is None:
            ws.cell(1, 4).value = "Saat"

        for cell in ws[1]:
            cell.font = Font(bold=True)
            cell.alignment = Alignment(horizontal="center")

        ws.freeze_panes = "A2"

    # Tarih ve saat
    now = datetime.now()

    tarih = now.strftime("%d.%m.%Y")
    saat = now.strftime("%H:%M:%S")

    # Yeni kayıt
    ws.append([title, url, tarih, saat])

    # Son satırı biçimlendir
    row = ws.max_row

    ws.cell(row, 1).alignment = Alignment(
        vertical="top",
        wrap_text=True
    )

    ws.cell(row, 2).hyperlink = url
    ws.cell(row, 2).style = "Hyperlink"

    ws.cell(row, 3).alignment = Alignment(horizontal="center")
    ws.cell(row, 4).alignment = Alignment(horizontal="center")

    # Sütun genişlikleri
    widths = {
        "A": 55,
        "B": 65,
        "C": 14,
        "D": 12
    }

    for column, width in widths.items():
        ws.column_dimensions[column].width = width

    # Filtreyi tüm kayıtları kapsayacak şekilde güncelle
    ws.auto_filter.ref = f"A1:D{ws.max_row}"

    # Kaydet
    wb.save(EXCEL_FILE)

    print(f"[Excel] Kayıt eklendi: {title}")
    print(f"[Excel] Dosya: {EXCEL_FILE}")


@app.route('/kaydet', methods=['POST'])
def kaydet():
    # JSON verisini al
    data = request.get_json(silent=True) or {}

    title = data.get('title')
    url = data.get('url')

    if title and url:
        try:
            excel_yaz(title, url)

            response = jsonify({
                "status": "Basarili"
            })

        except Exception as e:
            print("[Excel] HATA:", e)

            response = jsonify({
                "status": "Hata",
                "message": str(e)
            })

            response.status_code = 500

    else:
        response = jsonify({
            "status": "Eksik veri"
        })

        response.status_code = 400

    # CORS
    response.headers.add(
        'Access-Control-Allow-Origin',
        '*'
    )

    response.headers.add(
        'Access-Control-Allow-Headers',
        'Content-Type'
    )

    return response


@app.route('/kaydet', methods=['OPTIONS'])
def options():
    response = jsonify({})

    response.headers.add(
        'Access-Control-Allow-Origin',
        '*'
    )

    response.headers.add(
        'Access-Control-Allow-Headers',
        'Content-Type'
    )

    response.headers.add(
        'Access-Control-Allow-Methods',
        'POST, OPTIONS'
    )

    return response


if __name__ == '__main__':
    print("Excel Sunucusu Başlatıldı! İstekler bekleniyor...")
    print("http://127.0.0.1:5000")

    app.run(
        host='127.0.0.1',
        port=5000,
        threaded=True
    )

1786388449548.webp


1786388326582.webp
 
Geri
Üst