Python - 每次使用不同的信息多次运行代码[关闭]

问题描述 投票:-11回答:1

我希望以下代码运行x次,每次使用不同的代理。列表代理将存储在.txt文件中。重要的是不要多次使用代理。

headers = {'Host': 'google.com'}
URL = 'https://google.com'

proxies = {'https': 'https://USERNAME:PASSWORD@IP:PORT'}

r = requests.get(URL, headers=headers, proxies=proxies)

文本文件将采用以下格式:

IP:PORT:USERNAME:PASSWROD
IP:PORT:USERNAME:PASSWROD
IP:PORT:USERNAME:PASSWROD
IP:PORT:USERNAME:PASSWROD
IP:PORT:USERNAME:PASSWROD
IP:PORT:USERNAME:PASSWROD
IP:PORT:USERNAME:PASSWROD
IP:PORT:USERNAME:PASSWROD

非常感谢您对此的帮助 - 非常感谢!

python python-3.x
1个回答
1
投票

这是你怎么做的:

# Read lines from file.
proxy_lines = []
with open('proxies.txt', 'r') as proxy_file:
    proxy_lines = proxy_file.read().splitlines()

proxies = []
for line in proxy_lines:
    # Separate fields
    proxies.append(line.split(":"))

IP_INDEX = 0
PORT_INDEX = 1
USERNAME_INDEX = 2
PASSWORD_INDEX = 3

headers = {'Host': 'google.com'}
URL = 'https://google.com'

for proxy in proxies:
    # Format according to how request.get() wants the information.
    proxy_str = '{usr}:{pw}@{ip}:{prt}'.format(
        usr=proxy[USERNAME_INDEX], pw=proxy[PASSWORD_INDEX],
        ip=proxy[IP_INDEX], prt=proxy[PORT_INDEX])
    p_in = {'https': proxy_str}
    r = requests.get(URL, headers=headers, proxies=p_in)
© www.soinside.com 2019 - 2024. All rights reserved.