Maxsior
@Maxsior
loading...

Почему запрос не проходит через proxy(python)?

недавно начал изучать python, столкнулся с такой проблемой: пытаюсь сделать запрос через proxy сервер, почитал документацию, все правильно сделал, вроде, но почему-то не работает.
Проверяю так: скачиваю страницу, пишу её в файл, смотрю есть ли надпись "используется" напротив пункта "прокси". =)
Подскажите, пожалуйста, в чем ошибка
from urllib import request
prox={"http": "http://107.170.106.64:8888"}
request.ProxyHandler(prox)
r=request.urlopen("http://2ip.ru")
f=open("site.html","w",encoding="utf-8")
f.write(r.read().decode("utf-8"))
f.close()
r.close()

P.S. версия 3.4
  • Вопрос задан
  • 9422 просмотра
Решения вопроса 1
Maxsior
@Maxsior Автор вопроса
loading...
Вот =)
prox={"http": "http://107.170.106.64:8888"}
opener = urllib.request.FancyURLopener(prox)
r = opener.open("http://2ip.ru/")
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
1nn0
@1nn0
Системный администратор\Фрилансер
Сам только изучаю Python, в документации так же есть вот такая штука:
Request.set_proxy(host, type)
    Prepare the request by connecting to a proxy server. The host and type will replace those of the instance, and the instance’s selector will be the original URL given in the constructor.


И вот еще в той же документации:

ProxyHandler Objects

ProxyHandler.protocol_open(request)
    The ProxyHandler will have a method protocol_open() for every protocol which has a proxy in the proxies dictionary given in the constructor. The method will modify requests to go through the proxy, by calling request.set_proxy(), and call the next handler in the chain to actually execute the protocol.


Либо вот такая конструкция, взятая со StackOverflow (используется модуль requests, а не urllib)

http_proxy  = "http://10.10.1.10:3128"
https_proxy = "https://10.10.1.11:1080"
ftp_proxy   = "ftp://10.10.1.10:3128"

proxyDict = { 
              "http"  : http_proxy, 
              "https" : https_proxy, 
              "ftp"   : ftp_proxy
            }

r = requests.get(url, headers=headers, proxies=proxyDict)


Либо для Вашего кода нечто подобное:
prox={"http": "http://107.170.106.64:8888"}
hnd = request.ProxyHandler(prox)
opn = request.build_opener(hnd)
request.install_opener(opn)
Ответ написан
tenoclock
@tenoclock
Python/Django программист
В python 2.7 это реализуется как-то так
import urllib2

prox = urllib2.ProxyHandler({"http":"http://107.170.106.64:8888"})
opener = urllib2.build_opener(prox)
urllib2.install_opener(opener)

html = urllib2.urlopen("http://2ip.ru").read()

with open("site.html","w",encoding="utf-8") as f:
    f.write(html)


ещё есть модуль requests, который поддерживает прокси.

f.write(requests.get("http://2ip.ru", proxies={"http": "http://107.170.106.64:8888"}).text)
соответсвенно
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы