Python urllib2 proxy


在 正式並入某大公司之后,網絡必須設置為統一的proxy,好的方面沒看到,但是立即讓我一的一個小工具不能工作了。
在之前使用urllib2庫,無需設置proxy,一切工作正常。在必須使用proxy之后,遇到了一系列的問題

1. 使用urllib2的proxy

import urllib2

enable_proxy = True
proxy_handler = urllib2.ProxyHandler({"http" : 'your_proxy'})
null_proxy_handler = urllib2.ProxyHandler({})

if enable_proxy:
    opener = urllib2.build_opener(proxy_handler)
else:
    opener = urllib2.build_opener(null_proxy_handler)

urllib2.install_opener(opener)

 
結果得到錯誤如下:
URLError: <urlopen error [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
2. 使用requests

import requests
r = requests.get("http://www.google.com", proxies={"http": "your_proxy"})
print r.text

 結果:
可以訪問,但是內容不對

3. 使用requests的proxy

r = requests.get('http://www.thepage.com', proxies={"http":"your_proxy"})
print r.content

 4. 使用https_proxy

import requests

proxies = {
  "http": "your_http_proxy",
  "https": "your_https_proxy",
}

r = requests.get("http://www.google.com", proxies=proxies)
print r.content

 結果:
可以訪問,內容不對
4. 使用selenium

from selenium import webdriver
driver = webdriver.Chrome()
driver.get(url)
html_resource = driver.page_source

 結果:可以訪問,內容正確


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM