oct*_*pus 3 python attributes python-requests
我正在使用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.
^
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 11
一般来说,您可以使用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']
Run Code Online (Sandbox Code Playgroud)
您也可以只使用该help()函数,Python 将格式化类上的文档字符串;response.url没有一个文档字符串,但是在属性节中列出。
对于requests具体而言,刚检查出优秀的API文档。该url属性被列为Response对象的一部分。