使用代理时 python 请求出现问题

problem with python requests while using proxies

我正在尝试使用 python 请求来抓取网站。我们只能使用代理来抓取网站,所以我为此实现了代码。然而,即使我正在使用代理,它也会禁止我的所有请求,所以我使用了一个网站 https://api.ipify.org/?format=json 来检查代理是否正常工作。我发现即使在使用代理时它也会显示我的原始 IP。代码如下

from concurrent.futures import ThreadPoolExecutor

import string, random

import requests

import sys



http = []

#loading http into the list
with open(sys.argv[1],"r",encoding = "utf-8") as data:

    for i in data:
        http.append(i[:-1])
    data.close()

url = "https://api.ipify.org/?format=json"

def fetch(session, url):
    
for i in range(5):
    
      
                proxy = {'http': 'http://'+random.choice(http)}

               
                try:
                        with session.get(url,proxies = proxy, allow_redirects=False) as response:
                            print("Proxy : ",proxy," | Response : ",response.text)
                            break
                except:
                        pass



# @timer(1, 5)

if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=1) as executor:
        with requests.Session() as session:
            executor.map(fetch, [session] * 100, [url] * 100)
            executor.shutdown(wait=True)

我尝试了很多但不明白如何显示我的 ip 地址而不是代理 ipv4。您将在此处找到代码的输出 https://imgur.com/a/z02uSvi

您为 http 设置代理并向使用 https 的网站发送请求的问题。解决方法很简单:

proxies = dict.fromkeys(('http', 'https', 'ftp'), 'http://' + random.choice(http))
# You can set proxy for session
session.proxies.update(proxies)
response = session.get(url)
# Or you can pass proxy as argument
response = session.get(url, proxies=proxies)