셀레니움 윈도우용 크롬드라이버 자동설치, 프록시 적용버전

import subprocess
import xml.etree.ElementTree as elemTree
import urllib
import urllib.request
import zipfile, requests
import subprocess, re
class ChromeAutoinstaller:
    def __init__(self, proxyHost):
        self.proxyHost = proxyHost

    def get_chrome_version(self):
        process = subprocess.Popen(
            ['reg', 'query', 'HKEY_CURRENT_USER\\Software\\Google\\Chrome\\BLBeacon', '/v', 'version'],
            stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL
        )
        output = process.communicate()
        if output and output[0] and len(output[0]) > 0:
            version = output[0].decode('UTF-8').strip().split()[-1]
        else:
            process = subprocess.Popen(
                ['powershell', '-command', '$(Get-ItemProperty -Path Registry::HKEY_CURRENT_USER\\Software\\Google\\chrome\\BLBeacon).version'],
                stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE
            )
            version = process.communicate()[0].decode('UTF-8').strip()
        return version

    def get_platform_architecture(self):
        if sys.platform.startswith('linux') and sys.maxsize > 2 ** 32:
            platform = 'linux'
            architecture = '64'
        elif sys.platform == 'darwin':
            platform = 'mac'
            architecture = '64'
        elif sys.platform.startswith('win'):
            platform = 'win'
            architecture = '32'
        else:
            raise RuntimeError('Could not determine chromedriver download URL for this platform.')
        return platform, architecture

    def get_chromedriver_url(self, version, no_ssl=False):
        if no_ssl:
            base_url = 'http://chromedriver.storage.googleapis.com/'
        else:
            base_url = 'https://chromedriver.storage.googleapis.com/'
        platform, architecture = self.get_platform_architecture()
        return base_url + version + '/chromedriver_' + platform + architecture + '.zip'

    def get_matched_chromedriver_version(self, version, no_ssl=False):
        if no_ssl:
            doc = urllib.request.urlopen('http://chromedriver.storage.googleapis.com').read()
        else:
            doc = urllib.request.urlopen('https://chromedriver.storage.googleapis.com').read()
        root = elemTree.fromstring(doc)
        for k in root.iter('{http://doc.s3.amazonaws.com/2006-03-01}Key'):
            if k.text.find(self.get_major_version(version) + '.') == 0:
                return k.text.split('/')[0]
        return

    def get_major_version(self, version):
        return version.split('.')[0]

    def download_chromedriver(self, path=None, no_ssl=False):
        chrome_version = self.get_chrome_version()
        if not chrome_version:
            print('Chrome is not installed.')
            return
        chromedriver_version = self.get_matched_chromedriver_version(chrome_version, no_ssl)
        if not chromedriver_version:
            print('Can not find chromedriver for currently installed chrome version.')
            return
        major_version = self.get_major_version(chromedriver_version)

        if path:
            if not os.path.isdir(path):
                raise ValueError(f'Invalid path: {path}')
            chromedriver_dir = os.path.join(
                os.path.abspath(path),
                major_version
            )
        else:
            chromedriver_dir = os.path.join(
                os.path.abspath(os.path.dirname(__file__)),
                major_version
            )
        chromedriver_filename = 'chromedriver.exe'
        chromedriver_filepath = os.path.join(chromedriver_dir, chromedriver_filename)
        if not os.path.isfile(chromedriver_filepath) or \
                not self.check_version(chromedriver_filepath, chromedriver_version):
            print(f'Downloading chromedriver ({chromedriver_version})...')
            if not os.path.isdir(chromedriver_dir):
                os.makedirs(chromedriver_dir)
            url = self.get_chromedriver_url(version=chromedriver_version, no_ssl=no_ssl)
            try:

                session = requests.Session()

                session.proxies = {
                    'http': self.proxyHost,
                    'https': self.proxyHost,
                }
                with open('driver.zip', 'wb') as f:
                    f.write(session.get(url).content)
            except:
                raise RuntimeError(f'Failed to download chromedriver archive: {url}')

            driver_zip = zipfile.ZipFile(os.path.abspath('driver.zip'))
            driver_zip.extract(chromedriver_filename, chromedriver_dir)
            driver_zip.close()
        else:
            print('Chromedriver is already installed.')
        if not os.access(chromedriver_filepath, os.X_OK):
            os.chmod(chromedriver_filepath, 0o744)
        return chromedriver_filepath

    def check_version(self, binary, required_version):
        try:
            version = subprocess.check_output([binary, '-v'])
            version = re.match(r'.*?([\d.]+).*?', version.decode('utf-8'))[1]
            if version == required_version:
                return True
        except Exception:
            return False
        return False

autoinstall = ChromeAutoinstaller()
chrome_version = autoinstall.download_chromedriver("http://0.0.0.0:0")

19 thoughts on “셀레니움 윈도우용 크롬드라이버 자동설치, 프록시 적용버전”

  1. # Harvard University: A Legacy of Excellence and Innovation

    ## A Brief History of Harvard University

    Founded in 1636, **Harvard University** is the oldest
    and one of the most prestigious higher education institutions in the United States.

    Located in Cambridge, Massachusetts, Harvard has built a global reputation for academic excellence, groundbreaking research, and
    influential alumni. From its humble beginnings as a small college established to educate clergy, it has
    evolved into a world-leading university that shapes the future
    across various disciplines.

    ## Harvard’s Impact on Education and Research

    Harvard is synonymous with **innovation and intellectual leadership**.
    The university boasts:

    – **12 degree-granting schools**, including the renowned **Harvard Business School**,
    **Harvard Law School**, and **Harvard Medical School**.

    – **A faculty of world-class scholars**, many of whom are
    Nobel laureates, Pulitzer Prize winners, and pioneers in their fields.

    – **Cutting-edge research**, with Harvard leading initiatives in artificial intelligence,
    public health, climate change, and more.

    Harvard’s contribution to research is immense, with billions of dollars allocated to
    scientific discoveries and technological advancements each year.

    ## Notable Alumni: The Leaders of Today and Tomorrow

    Harvard has produced some of the **most influential figures** in history, spanning politics,
    business, entertainment, and science. Among them are:

    – **Barack Obama & John F. Kennedy** – Former U.S. Presidents

    – **Mark Zuckerberg & Bill Gates** – Tech visionaries
    (though Gates did not graduate)
    – **Natalie Portman & Matt Damon** – Hollywood icons
    – **Malala Yousafzai** – Nobel Prize-winning activist

    The university continues to cultivate future leaders who shape industries and drive global progress.

    ## Harvard’s Stunning Campus and Iconic Library

    Harvard’s campus is a blend of **historical charm and modern innovation**.
    With over **200 buildings**, it features:

    – The **Harvard Yard**, home to the iconic **John Harvard Statue** (and the famous
    “three lies” legend).
    – The **Widener Library**, one of the largest university libraries in the world, housing **over 20 million volumes**.

    – State-of-the-art research centers, museums, and performing arts venues.

    ## Harvard Traditions and Student Life

    Harvard offers a **rich student experience**, blending academics
    with vibrant traditions, including:

    – **Housing system:** Students live in one of 12 residential houses, fostering a strong sense of community.

    – **Annual Primal Scream:** A unique tradition where students de-stress by running through Harvard Yard before finals!

    – **The Harvard-Yale Game:** A historic football rivalry that unites alumni
    and students.

    With over **450 student organizations**, Harvard students engage in a diverse range of extracurricular activities, from entrepreneurship to performing arts.

    ## Harvard’s Global Influence

    Beyond academics, Harvard drives change in **global policy, economics,
    and technology**. The university’s research impacts healthcare, sustainability,
    and artificial intelligence, with partnerships across industries worldwide.
    **Harvard’s endowment**, the largest of any university,
    allows it to fund scholarships, research, and public initiatives, ensuring a legacy of impact for generations.

    ## Conclusion

    Harvard University is more than just a school—it’s
    a **symbol of excellence, innovation, and leadership**.
    Its **centuries-old traditions, groundbreaking discoveries, and transformative education**
    make it one of the most influential institutions in the world.
    Whether through its distinguished alumni, pioneering research, or vibrant student life, Harvard continues to shape the future
    in profound ways.

    Would you like to join the ranks of Harvard’s legendary scholars?
    The journey starts with a dream—and an application!

    응답

Leave a Comment