urllib2를 사용하는 프록시
다음으로 URL을 엽니 다.
site = urllib2.urlopen('http://google.com')
그리고 제가하고 싶은 것은 제가 어딘가에서 말한 프록시와 같은 방식으로 연결하는 것입니다.
site = urllib2.urlopen('http://google.com', proxies={'http':'127.0.0.1'})
그러나 그것도 작동하지 않았습니다.
urllib2에 프록시 처리기와 같은 것이 있다는 것을 알고 있지만 해당 기능을 기억할 수 없습니다.
proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
ProxyHandler를 설치해야합니다.
urllib2.install_opener(
urllib2.build_opener(
urllib2.ProxyHandler({'http': '127.0.0.1'})
)
)
urllib2.urlopen('http://www.google.com')
환경 변수를 사용하여 프록시를 설정할 수 있습니다.
import os
os.environ['http_proxy'] = '127.0.0.1'
os.environ['https_proxy'] = '127.0.0.1'
urllib2
이런 식으로 프록시 핸들러를 자동으로 추가합니다. 다른 프로토콜에 대한 프록시를 별도로 설정해야합니다. 그렇지 않으면 실패합니다 (프록시를 통과하지 않는다는 점에서). 아래를 참조하십시오.
예를 들면 :
proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
# next line will fail (will not go through the proxy) (https)
urllib2.urlopen('https://www.google.com')
대신
proxy = urllib2.ProxyHandler({
'http': '127.0.0.1',
'https': '127.0.0.1'
})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
# this way both http and https requests go through the proxy
urllib2.urlopen('http://www.google.com')
urllib2.urlopen('https://www.google.com')
기본 시스템 프록시를 사용하려면 (예 : http_support 환경 변수에서) 다음이 현재 요청에 대해 작동합니다 (전역 적으로 urllib2에 설치하지 않음).
url = 'http://www.example.com/'
proxy = urllib2.ProxyHandler()
opener = urllib2.build_opener(proxy)
in_ = opener.open(url)
in_.read()
받아 들여진 대답에 덧붙여 : 내 scipt가 나에게 오류를 주었다.
File "c:\Python23\lib\urllib2.py", line 580, in proxy_open
if '@' in host:
TypeError: iterable argument required
해결책은 프록시 문자열 앞에 http : //를 추가하는 것입니다.
proxy = urllib2.ProxyHandler({'http': 'http://proxy.xy.z:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
One can also use requests if we would like to access a web page using proxies. Python 3 code:
>>> import requests
>>> url = 'http://www.google.com'
>>> proxy = '169.50.87.252:80'
>>> requests.get(url, proxies={"http":proxy})
<Response [200]>
More than one proxies can also be added.
>>> proxy1 = '169.50.87.252:80'
>>> proxy2 = '89.34.97.132:8080'
>>> requests.get(url, proxies={"http":proxy1,"http":proxy2})
<Response [200]>
In addition set the proxy for the command line session Open a command line where you might want to run your script
netsh winhttp set proxy YourProxySERVER:yourProxyPORT
run your script in that terminal.
참고URL : https://stackoverflow.com/questions/1450132/proxy-with-urllib2
'Program Tip' 카테고리의 다른 글
@IBDesignable 충돌 에이전트 (0) | 2020.10.28 |
---|---|
복합 기본 키와 고유 한 개체 ID 필드 (0) | 2020.10.28 |
MySQL에서 공백 앞에있는 모든 문자 가져 오기 (0) | 2020.10.28 |
Windows 배치 파일에 여러 색상을 사용하는 방법은 무엇입니까? (0) | 2020.10.28 |
목록에 대한 ViewModel 유효성 검사 (0) | 2020.10.28 |