【问题标题】:how to use a variable in a for loop outside the loop python如何在循环python之外的for循环中使用变量
【发布时间】:2020-11-18 22:33:02
【问题描述】:

当我将代理变量放在 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)

为了解释我在做什么,我在做一个同时打开多个窗口并且每个窗口都有自己唯一代理的shoe bot,我想将代理变量作为参数放在函数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

【问题讨论】:

    标签: python python-3.x list for-loop


    【解决方案1】:

    在保持变量类型与现在相同(str)的同时,我真的没有办法让它工作。如果在 for 循环内分配了一个值并在循环外访问,它将只保存在循环终止之前分配的最后一个值。

    最好的方法是创建一个列表变量并将值附加到循环内的列表中。之后,可以从结果列表中轻松访问所有值:

    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)
    

    根据以下 cmets 更新: 要在函数中使用结果变量而不为列表赋值,您只需将函数调用放在 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)
    

    编辑 2: 因此,我查看了您的函数,似乎很容易将其修改为使用列表而不是简单的字符串。这样,该函数将根据多个代理返回多个驱动程序的列表:

        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
    

    【讨论】:

    • 对不起,这个解决方案一点用都没有,我想做的是将for循环中使用的变量放入一个函数中,谢谢分享
    • 那么为什么你的函数不能使用列表呢?或者,将您的函数调用放在 for 循环中。
    • 对不起,我仍然是编程初学者,但函数已经在 for 循环编辑中:我将发布整个代码
    • @TahaDaboussi,我用不同的方法修改了我的答案。
    • 非常感谢您的帮助,被这个问题困扰了好几天,谢谢您
    猜你喜欢
    • 2020-04-05
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多