python url2lib HTTP Error 407

简介: 公司的网络环境是通过代理上网,用python url2lib普通的代理验证不能通过,示例代码: url = 'www.python.org' username = 'user' password = 'pass' password_mgr = urllib2.

公司的网络环境是通过代理上网,用python url2lib普通的代理验证不能通过,示例代码:

url = 'www.python.org'
username = 'user'
password = 'pass'
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# None, with the "WithDefaultRealm" password manager means
# that the user/pass will be used for any realm (where
# there isn't a more specific match).
password_mgr.add_password(None, url, username, password)
auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
print urllib2.urlopen("http://www.python.org")

 

仍然会报以下错误:

HTTP Error 407: Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request.

查了一下,发现跟公司网络代理使用NTLM验证有关,需要安装python ntml包来完成验证。

简单直接用 easy_install python-ntlm

安装好后下面是官方简单的连接代码:

import urllib2
from ntlm import HTTPNtlmAuthHandler

user = 'domain\user'
password = "pass"
url = "http://www.python.org"

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, password)
# create the NTLM authentication handler
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)

# create and install the opener
opener = urllib2.build_opener(auth_NTLM)
urllib2.install_opener(opener)

# retrieve the result
response = urllib2.urlopen(url)
print(response.read())

 一次性成功。

 

目录
相关文章
|
1天前
|
缓存 IDE Linux
Internal error. Please report to https://jb.gg/ide/critical-startup-errors
Internal error. Please report to https://jb.gg/ide/critical-startup-errors
5 0
|
3天前
|
Python
IDA3.12版本的python,依旧报错IDAPython: error executing init.py.No module named ‘impRefer to the message win
IDA3.12版本的python,依旧报错IDAPython: error executing init.py.No module named ‘impRefer to the message win
|
7天前
|
数据采集 JSON 网络协议
「Python系列」Python urllib库(操作网页URL对网页的内容进行抓取处理)
`urllib` 是 Python 的一个标准库,用于打开和读取 URLs。它提供了一组模块,允许你以编程方式从网络获取数据,如网页内容、文件等。
29 0
|
21天前
解决Error:All flavors must now belong to a named flavor dimension. Learn more at https://d.android.com
解决Error:All flavors must now belong to a named flavor dimension. Learn more at https://d.android.com
21 5
|
1月前
|
测试技术 API Python
Python3 新一代Http请求库Httpx使用(详情版)(下)
Python3 新一代Http请求库Httpx使用(详情版)
|
1月前
|
XML JSON API
Python3 新一代Http请求库Httpx使用(详情版)(上)
Python3 新一代Http请求库Httpx使用(详情版)
|
1月前
|
JSON 数据格式 Python
如何使用 Python 中的`requests`库发送 HTTP 请求?
【2月更文挑战第21天】【2月更文挑战第66篇】如何使用 Python 中的`requests`库发送 HTTP 请求?
|
1月前
|
Web App开发 测试技术 Python
使用 Python 结合 Selenium 访问一个 url
使用 Python 结合 Selenium 访问一个 url
25 0
|
1月前
|
Web App开发 安全 定位技术
关于使用 Python 和 Selenium chrome driver 访问 url 时修改 source ip 的问题
关于使用 Python 和 Selenium chrome driver 访问 url 时修改 source ip 的问题
59 0
|
1月前
|
Java 应用服务中间件
解决tomcat启动报错:无法在web.xml或使用此应用程序部署的jar文件中解析绝对的url [http:java.sun.com/jsp/jstl/core]
解决tomcat启动报错:无法在web.xml或使用此应用程序部署的jar文件中解析绝对的url [http:java.sun.com/jsp/jstl/core]
110 1