使用代理时python请求出现问题
我正在尝试使用python请求刮取一个网站。我们只能使用代理刮网站,所以我实现了代码。然而,即使在我使用代理的时候,它也会禁止我的所有请求,所以我使用了一个网站来检查代理是否正常工作。我发现它显示了我的原始IP,甚至在使用代理的时候。代码如下使用代理时python请求出现问题,python,python-3.x,python-requests,proxies,Python,Python 3.x,Python Requests,Proxies,我正在尝试使用python请求刮取一个网站。我们只能使用代理刮网站,所以我实现了代码。然而,即使在我使用代理的时候,它也会禁止我的所有请求,所以我使用了一个网站来检查代理是否正常工作。我发现它显示了我的原始IP,甚至在使用代理的时候。代码如下 from concurrent.futures import ThreadPoolExecutor import string, random import requests import sys http = [] #loading htt
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。您将在此处找到代码输出您为
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)
尝试向您添加具有相同值的
https
键proxy
dictionary.Awesome。现在它实际显示了代理ip地址。我想我应该只在这里使用https。然而,当我在不使用多线程的情况下尝试相同的代码时,它实际上起到了作用。最好始终使用3个键('http'
,'https'
和'ftp'
),这将保证请求仍将使用代理。使用多线程对第三部分库有影响,这很奇怪,可能还有其他问题。(:我们可以添加socks4和socks5而不创建单独的字典吗?@Lakshmipathi,要添加socks代理支持,您需要安装PySocks
,并使用版本指定协议。示例:'socks4://127.0.0.1:9000'
,'socks4a://127.0.0.1:9001'
(通过代理发送DNS查询),“socks5://127.0.0.1:9002”
,“socks5h://127.0.0.1:9003”
(通过代理发送DNS查询)。