0

我正在创建一个脚本,它将在 python 中调用一个 rest API 并以JSON格式吐出结果。我的代码中有一些追溯错误。我该如何解决这个问题。

'import sitecustomize' failed; use -v for traceback
Traceback (most recent call last):
  File "/home/Desktop/Sync.py", line 12, in <module>
    url = urllib2.Request(request)
  File "/usr/lib/python2.7/urllib2.py", line 202, in __init__
    self.__original = unwrap(url)
  File "/usr/lib/python2.7/urllib.py", line 1057, in unwrap
    url = url.strip()
  File "/usr/lib/python2.7/urllib2.py", line 229, in __getattr__
    raise AttributeError, attr
AttributeError: strip

这是代码:

import urllib2
import json
url = "http://google.com"
request = urllib2.Request(url)
request.add_header("Authorization","Basic xxxxxxxxxxxxxxxxxx")
socket = urllib2.urlopen(request)
data = json.dumps(socket)

hdrs = socket.headers
source = socket.read()
socket.close()

print "---- Headers -----"
print data
print "---- Source HTML -----"
print source
print "---- END -----"

value = 0
for line in source.splitlines():
    if not line.strip():  continue
    if line.startswith("value="):
        try:
            value = line.split("=")
        except IndexError:
            pass
    if value > 0:
        break

open("some.json", "w").write("value is: %d" % value)
4

2 回答 2

0

从类的文档Request

url 应该是一个包含有效 URL 的字符串。

您当前正在将另一个Request对象传递给它的构造函数,这就是您看到错误的原因。这样做的正确方法:

request=urllib2.Request( "http.google.com")
request.add_header("Authorization","Basic xxxxxxxxxxxxxxxxxxxxxxxx=")
socket = urllib2.urlopen(request)
于 2013-07-15T13:54:48.710 回答
0

你这里似乎有问题:

request=urllib2.Request( "http.google.com")
request.add_header("Authorization","Basic xxxxxxxxxxxxxxxxxxxxxxxx=")
url = urllib2.Request(request)
socket = urllib2.urlopen(url)

您正在尝试通过将 Request 对象传递给构造函数来创建名为“url”的 Request 对象。

请参阅http://docs.python.org/2/library/urllib2.html#urllib2.Request

尝试这个:

request=urllib2.Request( "http.google.com")
request.add_header("Authorization","Basic xxxxxxxxxxxxxxxxxxxxxxxx=")
socket = urllib2.urlopen(request)
于 2013-07-15T13:52:04.763 回答