Python '요청'모듈을 사용하는 프록시
Python 의 우수한 요청 모듈에 대한 짧고 간단한 것 입니다.
문서에서 변수 '프록시'에 포함되어야하는 것을 찾을 수없는 것 같습니다. 표준 "IP : PORT"값을 사용하여 dict을 보내면 2 개의 값을 요구하는 것을 거부했습니다. 첫 번째 값은 ip이고 두 번째 포트는 포트라고 생각합니다 (문서에서 다루지 않는 것 같아).
문서는 이것을 언급합니다.
프록시 – (선택 사항) 프록시의 URL에 대한 사전 매핑 프로토콜입니다.
그래서 나는 이것을 시도했다 ... 나는 무엇을해야합니까?
proxy = { ip: port}
dict에 넣기 전에 이것을 어떤 유형으로 변환해야합니까?
r = requests.get(url,headers=headers,proxies=proxy)
proxies
'DICT 구문입니다 {"protocol":"ip:port", ...}
. 이를 통해 http , https 및 ftp 프로토콜을 사용하는 요청에 대해 다른 (또는 동일한) 프록시를 지정할 수 있습니다 .
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)
으로부터 추론 requests
문서 :
파라미터 :
method
– 새로운 Request 객체의 메소드.
url
– 새 요청 오브젝트의 URL.
...
proxies
– (선택 사항) 프록시 의 URL에 대한 사전 매핑 프로토콜 . ...
Linux HTTP_PROXY
에서는 HTTPS_PROXY
, 및 FTP_PROXY
환경 변수 를 통해이를 수행 할 수도 있습니다 .
export HTTP_PROXY=10.10.1.10:3128
export HTTPS_PROXY=10.10.1.11:1080
export FTP_PROXY=10.10.1.10:3128
Windows에서 :
set http_proxy=10.10.1.10:3128
set https_proxy=10.10.1.11:1080
set ftp_proxy=10.10.1.10:3128
Jay는 이것을 지적 해 주셔서 감사합니다.
구문은 요청 2.0.0으로 변경되었습니다 .
URL에 스키마를 추가해야합니다. http://docs.python-requests.org/en/latest/user/advanced/#proxies
urllib에는 시스템의 프록시 설정을 선택하는 데 실제로 좋은 코드가 있으며 직접 사용할 수있는 올바른 형식으로되어 있습니다. 다음과 같이 사용할 수 있습니다.
import urllib
...
r = requests.get('http://example.org', proxies=urllib.request.getproxies())
정말 잘 작동하며 urllib은 Mac OS X 및 Windows 설정에 대해서도 알고 있습니다.
여기서 프록시 설명서를 참조 할 수 있습니다 .
프록시를 사용해야하는 경우 proxies 인수를 사용하여 모든 요청 방법에 대한 개별 요청을 구성 할 수 있습니다.
import requests
proxies = {
"http": "http://10.10.1.10:3128",
"https": "https://10.10.1.10:1080",
}
requests.get("http://example.org", proxies=proxies)
프록시에서 HTTP 기본 인증을 사용하려면 http : // user : password@host.com/ 구문을 사용하십시오.
proxies = {
"http": "http://user:pass@10.10.1.10:3128/"
}
The accepted answer was a good start for me, but I kept getting the following error:
AssertionError: Not supported proxy scheme None
Fix to this was to specify the http:// in the proxy url thus:
http_proxy = "http://194.62.145.248:8080"
https_proxy = "https://194.62.145.248:8080"
ftp_proxy = "10.10.1.10:3128"
proxyDict = {
"http" : http_proxy,
"https" : https_proxy,
"ftp" : ftp_proxy
}
I'd be interested as to why the original works for some people but not me.
Edit: I see the main answer is now updated to reflect this :)
If you'd like to persisist cookies and session data, you'd best do it like this:
import requests
proxies = {
'http': 'http://user:pass@10.10.1.0:3128',
'https': 'https://user:pass@10.10.1.0:3128',
}
# Create the session and set the proxies.
s = requests.Session()
s.proxies = proxies
# Make the HTTP request through the session.
r = s.get('http://www.showmemyip.com/')
here is my basic class in python for the requests module with some proxy configs and stopwatch !
import requests
import time
class BaseCheck():
def __init__(self, url):
self.http_proxy = "http://user:pw@proxy:8080"
self.https_proxy = "http://user:pw@proxy:8080"
self.ftp_proxy = "http://user:pw@proxy:8080"
self.proxyDict = {
"http" : self.http_proxy,
"https" : self.https_proxy,
"ftp" : self.ftp_proxy
}
self.url = url
def makearr(tsteps):
global stemps
global steps
stemps = {}
for step in tsteps:
stemps[step] = { 'start': 0, 'end': 0 }
steps = tsteps
makearr(['init','check'])
def starttime(typ = ""):
for stemp in stemps:
if typ == "":
stemps[stemp]['start'] = time.time()
else:
stemps[stemp][typ] = time.time()
starttime()
def __str__(self):
return str(self.url)
def getrequests(self):
g=requests.get(self.url,proxies=self.proxyDict)
print g.status_code
print g.content
print self.url
stemps['init']['end'] = time.time()
#print stemps['init']['end'] - stemps['init']['start']
x= stemps['init']['end'] - stemps['init']['start']
print x
test=BaseCheck(url='http://google.com')
test.getrequests()
It’s a bit late but here is a wrapper class that simplifies scraping proxies and then making an http POST or GET:
ProxyRequests
https://github.com/rootVIII/proxy_requests
i just made a proxy graber and also can connect with same grabed proxy without any input here is :
#Import Modules
from termcolor import colored
from selenium import webdriver
import requests
import os
import sys
import time
#Proxy Grab
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.sslproxies.org/")
tbody = driver.find_element_by_tag_name("tbody")
cell = tbody.find_elements_by_tag_name("tr")
for column in cell:
column = column.text.split(" ")
print(colored(column[0]+":"+column[1],'yellow'))
driver.quit()
print("")
os.system('clear')
os.system('cls')
#Proxy Connection
print(colored('Getting Proxies from graber...','green'))
time.sleep(2)
os.system('clear')
os.system('cls')
proxy = {"http": "http://"+ column[0]+":"+column[1]}
url = 'https://mobile.facebook.com/login'
r = requests.get(url, proxies=proxy)
print("")
print(colored('Connecting using proxy' ,'green'))
print("")
sts = r.status_code
참고URL : https://stackoverflow.com/questions/8287628/proxies-with-python-requests-module
'Programing' 카테고리의 다른 글
여러 개의 제출 버튼 장고 양식을 어떻게 만들 수 있습니까? (0) | 2020.06.19 |
---|---|
Netbeans에서 자동 들여 쓰기는 어떻게합니까? (0) | 2020.06.19 |
CSS3 스핀 애니메이션 (0) | 2020.06.19 |
웹 API 메시지 핸들러에서 사용자 정의 헤더 값을 추출하는 방법은 무엇입니까? (0) | 2020.06.19 |
테이블 셀 내용을 강제로 래핑하는 방법은 무엇입니까? (0) | 2020.06.19 |