简体   繁体   English

遍历python代理字典

[英]Iterating through python dictionary of proxies

So I am using the requests module, but I am trying to change the proxy every time a request is made (Ex, GET and POST). 因此,我使用了requests模块,但是每次尝试发出请求(例如Ex,GET和POST)时,我都试图更改代理。 I have a dictionary of all the proxies I want to use, but I am having trouble getting the request to actually work through iterating through the dictionary. 我有一个我要使用的所有代理的字典,但是我很难获得通过迭代字典来实际工作的请求。 I understand how to send a request with a single proxy, but again, I am not sure how to with changing each proxy after every request. 我了解如何通过单个代理发送请求,但是同样,我不确定在每次请求后如何更改每个代理。 This is not the current program I am trying to write, but similarly the task I am trying to accomplish: 这不是我要编写的当前程序,但是类似地,我要完成的任务是:

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()

Thanks to all who reply in advance. 感谢所有提前答复的人。 All help/input is greatly appreciated! 非常感谢所有帮助/投入!

You don't need a dictionary for your proxies. 您不需要代理字典。 Use a plain list: 使用普通列表:

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

Change your function req to accept the proxy as a parameter. 更改功能req接受代理作为一个参数。 Global variables are evil :) 全局变量是邪恶的:)

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

Then iterate 然后重复

for proxy in proxies:
    req(proxy)

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

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