我使用python-requests和一个lambda函数(如果你叫它别的什么,请纠正我)来获得一个url。由于url根据epoch()的值不同而不同,因此我想打印它以进行调试。
对我来说幸运的是,print(kiwi.url)可以工作,因为kiwi.url存在,但是为了将来的参考,我如何才能找到python请求的所有可能的属性,甚至其他模块,而不依赖于运气?
import time, requests
epoch = lambda: int(time.time()*1000)
kiwi = s.get('http://www.example.com/api?do=%i' % epoch())
print(kiwi.url) #I found the .url attribute by chance.
^发布于 2014-12-09 00:11:21
一般来说,您可以使用dir()和vars()函数来内省Python对象:
>>> import requests
>>> response = requests.get('http://httpbin.org/get?foo=bar')
>>> dir(response)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getstate__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'is_permanent_redirect', 'is_redirect', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
>>> 'url' in dir(response)
True
>>> vars(response).keys()
['cookies', '_content', 'headers', 'url', 'status_code', '_content_consumed', 'encoding', 'request', 'connection', 'elapsed', 'raw', 'reason', 'history']您也可以只使用help() function,Python将格式化类上的文档字符串;response.url没有文档字符串,但在attributes部分中列出。
对于requests,只需查看优秀的API documentation即可。url属性作为Response object的一部分列出。
发布于 2014-12-09 00:11:17
在shell中使用dir():
>>> import requests
>>> req = requests.get('http://www.google.com')
>>> dir(req)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__doc__',
'__format__', '__getattribute__', '__getstate__', '__hash__', '__init__',
'__iter__', '__module__', '__new__', '__nonzero__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed',
'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed',
'encoding', 'headers', 'history', 'is_redirect', 'iter_content', 'iter_lines',
'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request',
'status_code', 'text', 'url']https://stackoverflow.com/questions/27362049
复制相似问题