🔥 با کمک هوش مصنوعی در کمتر از 6 ماه فول‌استک شوید ...
۰ ثانیه
۰ دقیقه
۰ ساعت
۰ استاد نوگل نامور
MultiThread
جامعه پایتون (وب) ایجاد شده در ۰۷ اسفند ۱۴۰۰

سلام به دوستان عزیز خواستم ببینم ایا این کدی که بنده با توجه به دو سرفصل قبل نوشتم , بستری که برای thread فراهم کردم کلا راجب حرکت thread نظرتون چیه و ایا thread safe هست یا خیر؟

ممنون میشم کدمو بخونین و نظرتون بگین و راهنمایی کنین

import json
from abc import ABC, abstractmethod
import threading
import requests
from bs4 import BeautifulSoup
class CrawlBase(ABC):
    @abstractmethoddef start_crawl(self):
        pass
    @abstractmethoddef store(self, name, data):
        pass
class LinkCrawler(CrawlBase, threading.Thread):
    crawl_running = True
    def __init__(self, cities, link, queue, *args, **kwargs):
        self.queue = queue
        self.cities = cities
        self.link = link
        self.put_in()
        super().__init__(*args, **kwargs)
    def put_in(self):
        for city in self.cities:
            self.queue.put(city)
    def get_page(self, start, city):
        try:
            response = requests.get(self.link.format(city) + str(start))
        except TimeoutError:
            return Nonereturn response.text
    @staticmethoddef find_links(html_doc):
        soup = BeautifulSoup(html_doc, 'html.parser')
        return soup.find_all('a', attrs={'class': 'hdrlnk'})
    def start_crawl(self):
        city = self.queue.get()
        page = 0
        advertisement_links = list()
        while self.crawl_running:
            response = self.get_page(page, city)
            links = self.find_links(response)
            if not links:
                self.crawl_running = False
                self.queue.task_done()
            advertisement_links.extend(links)
            page += 120
        storage_list = [li.get('href') for li in advertisement_links]
        self.store(city, storage_list)
    def run(self):
        self.start_crawl()
    def store(self, name, data):
        with open(f'advertisements/links_{name}.json', 'w') as f:
            f.write(json.dumps(data))

بالایی فایل crawl.py هست و پایینی فایل main.py

from crawl import LinkCrawler
from config import cities, link, q
if __name__ == "__main__":
    for i in range(4):
        c1 = LinkCrawler(cities, link, q)
        c1.start()