对于侧面项目,我试图通过NS api对NS(Nederlandse Spoorwegen)数据进行一些分析。
奇怪的是,从http://webservices.ns.nl/ns-api-avt?station=Dordrecht获取电台信息非常有效,但尝试从http://webservices.ns.nl/ns-api-stations获取所有电台会导致HTTP错误。使用:
import urllib2
from xml.etree import ElementTree
import datetime, time, sys
theurl = 'http://webservices.ns.nl/ns-api-avt'
username = 'username'
password = 'password'
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
specificURL = 'http://webservices.ns.nl/ns-api-avt?station=Dordrecht'
xmlHandle = urllib2.urlopen(specificURL)
不起作用:
theurl = 'http://webservices.ns.nl/ns-api-avt'
username = 'username'
password = 'password'
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
specificURL = "http://webservices.ns.nl/ns-api-stations"
xmlHandle = urllib2.urlopen(specificURL)
这两个例程是相同的,但会产生不同的结果。我错过了什么吗?
错误代码:
File "stations.py", line 32, in <module>
xmlHandle = urllib2.urlopen(specificURL)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized
答案 0 :(得分:0)
(部分)已解决
代码,简单如下:
import requests
url = 'http://webservices.ns.nl/ns-api-stations-v2'
username = 'username'
password = 'password'
print(requests.get(url, auth=(username, password)).content)
作品!两个网址。奇怪的是,另一种方式对两者都不起作用,但只针对一种方式。