Requests.history不打印python3

时间:2017-09-12 05:30:04

标签: python-3.x python-requests

我是python编程的菜鸟。我有一个简单的问题。我在pyCharm 2017.2.1中使用python3,我想打印出所有请求重定向。从我用谷歌搜索,我似乎做得对。我没有错误和回复200.我错过了什么?

import requests
url='http://httpbin.org/html'
payload= {'url':'http://bing.com'}

req = requests.get(url, params=payload)
#print(req.text)
print("Response code: " + str(req.status_code))

if req.history:
    print ("Request was redirected")
    for resp in req.history:
        print (resp.status_code, resp.url)
        print ( "Final destination:")
        print(resp.status_code, resp.url)
    else:
        print("Request was not redirected")


for x in req.history:
    print(str(x.status_code) + ' : ' + x.url)

输出:

Response code: 200

Process finished with exit code 0

1 个答案:

答案 0 :(得分:0)

我认为你应该使用这个网址:http://httpbin.org/redirect-to, 您使用的网址不会重定向您的请求。此外,还没有执行else块,因为它适用于for循环。

import requests

url='http://httpbin.org/redirect-to'
payload= {'url':'http://bing.com'}
req = requests.get(url, params=payload)

print("Response code: " + str(req.status_code))
if req.history:
    print ("Request was redirected")
    for resp in req.history:
        print("Final destination:")
        print(resp.status_code, resp.url)
else:
    print("Request was not redirected")

for x in req.history:
    print(str(x.status_code) + ' : ' + x.url)

请注意,如果将allow_redirects参数设置为False

,则可以停用重定向