Anda ingin memodifikasi skrip Python ini agar dapat memuat target URL dari file target.txt tanpa perlu konfirmasi berulang kali. Ini dapat dilakukan dengan membaca setiap baris dari target.txt sebagai URL dan memprosesnya secara otomatis.

Berikut adalah skrip Python yang sudah dimodifikasi:

import os
import requests
from bs4 import BeautifulSoup
import pyfiglet
from colorama import init, Fore

# Initialize colorama
init(autoreset=True)

# Function to fetch links from a webpage, count them, and save them to a text file grouped by domain
def fetch_links_and_save(url):
    try:
        print(Fore.CYAN + f"[*] Mengambil tautan dari: {url}")
        # Send an HTTP GET request to the URL
        response = requests.get(url, timeout=10) # Added timeout for robustness
        
        # Check if the request was successful
        if response.status_code == 200:
            # Parse the HTML content of the page using BeautifulSoup
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # Find all the anchor tags (<a>) in the page
            links = soup.find_all('a', href=True)
            
            # Extract the links and group them by domain
            link_groups = {}
            for link in links:
                href = link['href']
                # Basic check for valid URL format
                if href.startswith('http://') or href.startswith('https://'):
                    try:
                        domain = href.split('/')[2]
                        if domain not in link_groups:
                            link_groups[domain] = []
                        link_groups[domain].append(href)
                    except IndexError:
                        # Handle cases where href might not have a proper domain part
                        if 'Other' not in link_groups:
                            link_groups['Other'] = []
                        link_groups['Other'].append(href)
                else:
                    if 'Other' not in link_groups:
                        link_groups['Other'] = []
                    link_groups['Other'].append(href)

            # Save the grouped links to a text file
            with open('links.txt', 'a') as file: # Changed to 'a' (append) mode
                file.write(f"\n--- Tautan dari: {url} ---\n")
                for domain, domain_links in link_groups.items():
                    file.write(f"\n{domain} Links:\n")
                    for link in domain_links:
                        file.write(link + '\n')
            
            print(Fore.GREEN + f'[*] Total {len(links)} tautan berhasil disimpan ke links.txt dari {url}')
        else:
            print(Fore.RED + f'[-] Gagal mengambil halaman web dari {url}. Kode status: {response.status_code}')
    except requests.exceptions.RequestException as e:
        print(Fore.RED + f'[-] Terjadi kesalahan koneksi saat mengakses {url}: {e}')
    except Exception as e:
        print(Fore.RED + f'[-] Terjadi kesalahan: {e} saat memproses {url}')

if __name__ == "__main__":
    # Create an ASCII art heading using pyfiglet
    heading = pyfiglet.figlet_format("Link Scraper", font="slant")
    
    # Clear the terminal screen
    os.system('cls' if os.name == 'nt' else 'clear')
    print(Fore.CYAN + heading)
    
    # Hero section with credits and GitHub link
    print(Fore.MAGENTA + "Author: Harindu Jayakody")
    print(Fore.MAGENTA + "GitHub Repo 🩷: https://github.com/harindujayakody/fetches-all-links\n")
    
    # Ensure links.txt is empty before starting
    with open('links.txt', 'w') as file:
        file.write('')
    
    target_file = 'target.txt'
    
    if not os.path.exists(target_file):
        print(Fore.RED + f"File '{target_file}' tidak ditemukan. Harap buat file ini dan tambahkan URL di setiap baris.")
    else:
        with open(target_file, 'r') as f:
            urls = [line.strip() for line in f if line.strip()] # Read non-empty lines
        
        if not urls:
            print(Fore.YELLOW + f"File '{target_file}' kosong. Harap tambahkan URL ke file tersebut.")
        else:
            for url in urls:
                fetch_links_and_save(url)
                print("-" * 50) # Separator for better readability

    print(Fore.CYAN + "\n[*] Proses selesai.")


Perubahan Utama

  1. Hapus Konfirmasi:
    • Fungsi ask_for_retry_or_close() telah dihapus karena tidak diperlukan lagi.
    • Loop while True yang meminta input URL telah dihapus.
  2. Baca dari target.txt:
    • Skrip sekarang memeriksa keberadaan file target.txt.
    • Jika file ditemukan, skrip akan membaca setiap barisnya. Setiap baris yang tidak kosong akan dianggap sebagai URL target.
    • Setiap URL kemudian dilewatkan ke fungsi fetch_links_and_save() secara berurutan.
  3. Mode Penulisan File links.txt:
    • Mode pembukaan file links.txt diubah dari 'w' (write/overwrite) menjadi 'a' (append) di dalam fungsi fetch_links_and_save(). Ini memastikan bahwa tautan dari setiap URL target ditambahkan ke file yang sama, bukan menimpa data sebelumnya.
    • Sebelum memulai proses, links.txt akan dikosongkan sekali untuk memastikan data baru.
  4. Penanganan Kesalahan dan Pesan:
    • Ditambahkan penanganan untuk kasus di mana target.txt tidak ditemukan atau kosong.
    • Pesan output telah diperbarui untuk menunjukkan URL yang sedang diproses dan memberikan indikasi kemajuan.
    • Ditambahkan timeout pada requests.get() untuk membuat skrip lebih tangguh terhadap koneksi yang lambat atau tidak responsif.
    • Penanganan IndexError untuk href.split('/')[2] jika href tidak memiliki bagian domain yang diharapkan.

Cara Penggunaan:

  1. Buat file target.txt: Di direktori yang sama dengan skrip Python Anda, buat file teks baru bernama target.txt.

Jalankan Skrip: Jalankan skrip Python seperti biasa:Bash

python nama_script_anda.py

Tambahkan URL: Masukkan setiap URL yang ingin Anda scrape ke dalam file target.txt, satu URL per baris. Contoh:

https://www.example.com
https://www.google.com
https://www.github.com

Skrip akan secara otomatis membaca URL dari target.txt, mengambil semua tautan dari setiap URL, dan menyimpannya ke links.txt tanpa memerlukan interaksi pengguna.