简体   繁体   English

如何在循环外的for循环中使用变量python

[英]how to use a variable in a for loop outside the loop python

when I put the proxy variable inside the for loop the code work fine, but when I print proxy outside the for loop it only give the first loop and stops, is there a way the proxy variable work fine if i used it outside the for loop.当我将代理变量放在 for 循环中时,代码工作正常,但是当我在 for 循环外打印代理时,它只给出第一个循环并停止,如果我在 for 循环外使用它,代理变量是否可以正常工作.

value = ['3128', '3128', '3128', '3128']
num = ['40.69.144.143', '40.69.144.143', '40.69.144.143', '40.69.144.143']
for (a, c) in zip(num,value):
    proxy = a+':'+c
        print(proxy)

to explain what am doing, am doing a shoe bot that open multiple windows at the same time and each window has its own unique proxy, I want to put the proxy variable in the function get_chromedriver as a parameter.为了解释我在做什么,我正在做一个同时打开多个窗口的鞋机器人,每个窗口都有自己唯一的代理,我想将代理变量放在函数 get_chromedriver 中作为参数。

from selenium import webdriver
import threading
import time
import zipfile

    proxy_host = ['40.122.24.111', '40.122.24.111', '40.122.24.111', '40.122.24.111']  # rotating proxy
    proxy_port = ['3128', '3128', '3128', '3128']
    proxy_username = ['lukmanaraby', 'lukmanaraby', 'lukmanaraby', 'lukmanaraby']
    proxy_password = ['aiobotagents', 'aiobotagents', 'aiobotagents', 'aiobotagents']
 for (a, c) in zip(proxy_host,proxy_port):
        proxy = a+':'+c
 
    
    def test_logic():
        url = 'https://whatismyipaddress.com/'
        webdriver.Chrome("C:\Program Files (x86)\chromedriver.exe", options=chrome_options).get(url)
        # Implement your test logic
    def auth_json(host,port,user,password):
        global manifest_json
        global background_js
        manifest_json  = """
    {
        "version": "1.0.0",
        "manifest_version": 2,
        "name": "Chrome Proxy",
        "permissions": [
            "proxy",
            "tabs",
            "unlimitedStorage",
            "storage",
            "<all_urls>",
            "webRequest",
            "webRequestBlocking"
        ],
        "background": {
            "scripts": ["background.js"]
        },
        "minimum_chrome_version":"22.0.0"
    }
    """
    
        background_js = """
    var config = {
            mode: "fixed_servers",
            rules: {
              singleProxy: {
                scheme: "http",
                host: "%s",
                port: parseInt(%s)
              },
              bypassList: ["localhost"]
            }
          };
    
    chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
    
    function callbackFn(details) {
        return {
            authCredentials: {
                username: "%s",
                password: "%s"
            }
        };
    }
    
    chrome.webRequest.onAuthRequired.addListener(
                callbackFn,
                {urls: ["<all_urls>"]},
                ['blocking']
    );
    """ % (host,port,user,password)
    
    
        #containing the authentication of the proxies.
    def proxy_auth(): #transfering the information of the proxies to auth_json function
     for (i,j,m,k) in zip(proxy_host, proxy_port, proxy_username, proxy_password):
        auth_json(i,j,m,k)
    def get_chromedriver(use_proxy=False, user_agent=proxy):
        global  chrome_options
        chrome_options = webdriver.ChromeOptions()
        if use_proxy:
            pluginfile = 'proxy_auth_plugin.zip'
    
            with zipfile.ZipFile(pluginfile, 'w') as zp:
                zp.writestr("manifest.json", manifest_json)
                zp.writestr("background.js", background_js)
            chrome_options.add_extension(pluginfile)
        if user_agent==proxy:
            chrome_options.add_argument('--proxy-server=%s' % user_agent)
        driver = webdriver.Chrome("C:\Program Files (x86)\chromedriver.exe",options=chrome_options)
        return driver
    
    N = 5   # Number of browsers to spawn
    thread_list = list()
    
    # Start test
    for i in proxy_host:
        get_chromedriver()
        proxy_auth()
        t = threading.Thread(name='Test {}'.format(i), target=test_logic)
        t.start()
        time.sleep(1)
        print (t.name + ' started!')
        thread_list.append(t)
    
    # Wait for all thre<ads to complete
    for thread in thread_list:
        thread.join()
    
    print ('Test completed!')
        enter code here

There's really no way I can think of to make it work while keeping variable type the same as it is right now (str).我真的没有办法让它工作,同时保持变量类型与现在相同(str)。 If assigned a value inside a for loop and accessed outside the loop it will only hold the last value it was assigned before the loop terminated.如果在for循环内分配了一个值并在循环外访问,它将只保存在循环终止之前分配的最后一个值。

The best way to do it is to create a list variable and append values to the list inside the loop.最好的方法是创建一个列表变量并将值附加到循环内的列表中。 After that all values can be easily accessed from the resulting list:之后,可以从结果列表中轻松访问所有值:

value = ['3128', '3128', '3128', '3128']
num = ['40.69.144.143', '40.69.144.143', '40.69.144.143', '40.69.144.143']
proxy = []
for (a, c) in zip(num,value):
    proxy.append(a+':'+c)

for item in proxy:
    print(item)

Updated as per comments below: To use resulting variable in a function without assigning values to a list you can just put the function call inside the for loop.根据以下评论更新:要在函数中使用结果变量而不将值分配给列表,您只需将函数调用放在for循环中。

def my_func(a):
   return a

value = ['3128', '3128', '3128', '3128']
num = ['40.69.144.143', '40.69.144.143', '40.69.144.143', '40.69.144.143']

for (a, c) in zip(num,value):
    proxy.append(a+':'+c)
    foo = my_func(proxy)

EDIT 2: So I had a look at your function and it seems like and easy fix to modify it to use lists instead of simple strings.编辑 2:所以我查看了您的函数,修改它以使用列表而不是简单的字符串似乎很容易修复。 This way the function will return a list of multiple drivers based on multiple proxies:这样,该函数将基于多个代理返回多个驱动程序的列表:

    def get_chromedriver(use_proxy=False, user_agent: list = proxy):
        global  chrome_options
        chrome_options = webdriver.ChromeOptions()
        if use_proxy:
            pluginfile = 'proxy_auth_plugin.zip'
    
            with zipfile.ZipFile(pluginfile, 'w') as zp:
                zp.writestr("manifest.json", manifest_json)
                zp.writestr("background.js", background_js)
            chrome_options.add_extension(pluginfile)
        drivers = []
        for i in user_agent:
            chrome_options.add_argument('--proxy-server=%s' % user_agent)
            drivers.append(webdriver.Chrome("C:\Program Files (x86)\chromedriver.exe",options=chrome_options))
        return drivers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM