繁体   English   中英

遍历python代理字典

[英]Iterating through python dictionary of proxies

因此,我使用了requests模块,但是每次尝试发出请求(例如Ex,GET和POST)时,我都试图更改代理。 我有一个我要使用的所有代理的字典,但是我很难获得通过迭代字典来实际工作的请求。 我了解如何通过单个代理发送请求,但是同样,我不确定在每次请求后如何更改每个代理。 这不是我要编写的当前程序,但是类似地,我要完成的任务是:

BASE_URL = "Some url"
USER_AGENT = "Some user agent"
POST_URL = "Some url"

proxies = {
    'https' : 'proxy1',
    'https' : 'proxy2',
    'https' : 'proxy...'
}


def req():

        session = requests.Session()
        session.headers = {'user-agent': USER_AGENT}
        session.headers.update({'Referer': BASE_URL})
        req = session.get(BASE_URL, proxies=curProxy)

        session.headers.update({'x-csrftoken': req.cookies['csrftoken']})
        login_data = {'DATA HERE'}
        login = session.post(POST_URL, data=login_data, allow_redirects=True, proxies=curProxy)
        session.headers.update({'x-csrftoken': login.cookies['csrftoken']})
        cookies = login.cookies



# For each proxy in proxies
for proxy in proxies:
    # Updating the proxy to use
    curProxy = proxy
    req()

感谢所有提前答复的人。 非常感谢所有帮助/投入!

您不需要代理字典。 使用普通列表:

proxies = ['proxy1', 'proxy2', ...]

更改功能req接受代理作为一个参数。 全局变量是邪恶的:)

def req(curProxy):
    ...
    req = session.get(BASE_URL, proxies={'http': curProxy, 'https': curProxy})

然后重复

for proxy in proxies:
    req(proxy)

暂无
暂无

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

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