与Python混淆并且我尝试使用此https://updates.opendns.com/nic/update?hostname=,当您到达URL时,它将提示用户名和密码。我一直在四处寻找密码管理器,所以我提出了这个问题:
urll = "http://url.com"
username = "username"
password = "password"
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, urll, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
urllib2 = urllib2.build_opener(authhandler)
pagehandle = urllib.urlopen(urll)
print (pagehandle.read())
这一切都有效,但是它通过命令行提示用户名和密码,需要用户进行交互。我希望它自动输入这些值。我做错了什么?
答案 0 :(得分:11)
您可以使用requests代替。代码很简单:
import requests
url = 'https://updates.opendns.com/nic/update?hostname='
username = 'username'
password = 'password'
print(requests.get(url, auth=(username, password)).content)
答案 1 :(得分:2)
您的请求网址是"限制"。
如果您尝试此代码,它会告诉您:
import urllib2
theurl = 'https://updates.opendns.com/nic/update?hostname='
req = urllib2.Request(theurl)
try:
handle = urllib2.urlopen(req)
except IOError, e:
if hasattr(e, 'code'):
if e.code != 401:
print 'We got another error'
print e.code
else:
print e.headers
print e.headers['www-authenticate']
您应该添加授权标头。 有关详细信息,请查看:http://www.voidspace.org.uk/python/articles/authentication.shtml
另一个代码示例是: http://code.activestate.com/recipes/305288-http-basic-authentication/
如果您想发送POST请求,请尝试:
import urllib
import urllib2
username = "username"
password = "password"
url = 'http://url.com/'
values = { 'username': username,'password': password }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()
print result
注意:这只是如何将POST请求发送到网址的示例。
答案 2 :(得分:1)
我有一段时间没玩过python,但试试这个:
urllib.urlopen("http://username:password@host.com/path")