2026. június 26., péntek

Aszinkron vagy párhuzamos feladatvégzés

Egy komplexebb Python program tipikusan több egymással együttműködő modulból (objektum-orientált tervezés), hibakezelésből, külső könyvtárak használatából és aszinkron vagy párhuzamos feladatvégzésből épül fel.Íme egy gyakorlati példa egy többszálú (multithreading) webes adatgyűjtő (crawler) és adatfeldolgozó alkalmazásra, amely objektum-orientált felépítést alkalmaz:
---------------
import requests
import concurrent.futures
import logging
from urllib.parse import urlparse
from html.parser import HTMLParser
import time

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class SimpleHTMLParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.in_title = False
        self.title = ""
        self.paragraphs = []
        self.current_p = []
        self.in_p = False

    def handle_starttag(self, tag, attrs):
        if tag == "title":
            self.in_title = True
        if tag == "p":
            self.in_p = True
            self.current_p = []

    def handle_endtag(self, tag):
        if tag == "title":
            self.in_title = False
        if tag == "p":
            self.in_p = False
            text = "".join(self.current_p).strip()
            if text:
                self.paragraphs.append(text)

    def handle_data(self, data):
        if self.in_title:
            self.title += data
        if self.in_p:
            self.current_p.append(data)

class WebCrawler:
    def __init__(self, max_threads=5):
        self.max_threads = max_threads
        self.visited_urls = set()
        self.results = []

    def is_valid(self, url):
        parsed = urlparse(url)
        return bool(parsed.netloc) and bool(parsed.scheme)

    def scrape_page(self, url):
        logging.info(f"Oldal feldolgozása: {url}")
        try:
            response = requests.get(url, timeout=10)
            response.raise_for_status()

            parser = SimpleHTMLParser()
            parser.feed(response.text)

            title = parser.title.strip() if parser.title.strip() else "Nincs cím"
            paragraphs = parser.paragraphs

            return {
                "url": url,
                "title": title,
                "content_length": len(" ".join(paragraphs))
            }

        except requests.RequestException as e:
            logging.error(f"Hiba a(z) {url} letöltésekor: {e}")
            return None

    def crawl_site(self, start_urls):
        with concurrent.futures.ThreadPoolExecutor(max_workers=self.max_threads) as executor:
            future_to_url = {
                executor.submit(self.scrape_page, url): url
                for url in start_urls
                if url not in self.visited_urls
            }

            for future in concurrent.futures.as_completed(future_to_url):
                url = future_to_url[future]
                self.visited_urls.add(url)
                data = future.result()
                if data:
                    self.results.append(data)

if __name__ == "__main__":
    start_time = time.time()

    urls_to_crawl = [
        "https://python.org",
        "https://wikipedia.org",
        "https://github.com"
    ]

    crawler = WebCrawler(max_threads=3)
    crawler.crawl_site(urls_to_crawl)

    logging.info(f"Bejárt oldalak száma: {len(crawler.visited_urls)}")
    logging.info(f"Teljes futási idő: {time.time() - start_time:.2f} másodperc")

    for res in crawler.results:
        print(f"\nSikeres találat: {res['title']}\nURL: {res['url']}\nKarakterszám: {res['content_length']}")
----------------

2026-06-26 14:34:24,589 - INFO - Oldal feldolgozása: https://python.org
2026-06-26 14:34:24,589 - INFO - Oldal feldolgozása: https://wikipedia.org
2026-06-26 14:34:24,589 - INFO - Oldal feldolgozása: https://github.com
HTTPSConnectionPool(host='python.org', port=443): Max retries exceeded with url: / (Caused by NameResolutionError("HTTPSConnection(host='python.org', port=443): Failed to resolve 'python.org' ([Errno -3] Temporary failure in name resolution)"))
 HTTPSConnectionPool(host='wikipedia.org', port=443): Max retries exceeded with url: / (Caused by NameResolutionError("HTTPSConnection(host='wikipedia.org', port=443): Failed to resolve 'wikipedia.org' ([Errno -3] Temporary failure in name resolution)"))
 HTTPSConnectionPool(host='github.com', port=443): Max retries exceeded with url: / (Caused by NameResolutionError("HTTPSConnection(host='github.com', port=443): Failed to resolve 'github.com' ([Errno -3] Temporary failure in name resolution)"))
2026-06-26 14:34:24,592 - INFO - Bejárt oldalak száma: 3
2026-06-26 14:34:24,592 - INFO - Teljes futási idő: 0.00 másodperc

Nincsenek megjegyzések:

Megjegyzés küldése