使用代理时python请求的问题

问题描述

我正在尝试使用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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...