File size: 2,012 Bytes
fde6ce9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import zipfile
import os
import json
from selenium.webdriver.common.by import By


def replace_variables_in_js(js_content: str, variables_dict: dict):
    for variable, value in variables_dict.items():
        js_content = js_content.replace('{{ ' + variable + ' }}', value)
    return js_content


def generate_proxy_auth_extension(
        proxy_host: str, proxy_port: str, proxy_user: str, proxy_pass: str,
        extension_file: str):
    """Generate a Chrome extension that modify proxy settings based on desired host, port, username and password.

    If you are using --headless in chromedriver, you must use --headless=new to support extensions in headless mode.
    """
    current_dir = os.path.dirname(os.path.abspath(__file__))
    manifest_json_path = os.path.join(current_dir, 'manifest.json')
    background_js_path = os.path.join(current_dir, 'background.js')
    with open(manifest_json_path, 'r', encoding='utf-8') as f:
        manifest_json = f.read()
    with open(background_js_path, 'r', encoding='utf-8') as f:
        background_js = f.read()

    variables_dict = {
        'proxy_host': proxy_host,
        'proxy_port': proxy_port,
        'proxy_user': proxy_user,
        'proxy_pass': proxy_pass
    }
    background_js = replace_variables_in_js(background_js, variables_dict)

    with zipfile.ZipFile(extension_file, 'w') as zp:
        zp.writestr('manifest.json', manifest_json)
        zp.writestr('background.js', background_js)


def get_my_ip(driver):
    origin_tab = driver.current_window_handle
    driver.execute_script("window.open('', '_blank');")
    driver.switch_to.window(driver.window_handles[-1])

    driver.get('https://api.ipify.org/?format=json')

    ip_row = driver.find_element(By.XPATH, '//body').text
    ip = json.loads(ip_row)['ip']

    driver.close()
    driver.switch_to.window(origin_tab)

    return ip


def proxy_is_working(driver, host: str):
    ip = get_my_ip(driver)

    if ip == host:
        return True
    else:
        return False