我正在尝试使用下面的代码获取json格式的http端点数据,但我收到的输出并不像下面发布的链接那样可见。您能分享一下如何做到这一点吗?
代码: -
{u'Host': u'headers.jsontest.com', u'User-Agent': u'python-requests/2.18.4', u'Accept': u'*/*', u'X-Cloud-Trace-Context': u'9034981eba16654b42daa1d10f503cab/2431501768736408823'}
输出我收到的内容: -
{
"X-Cloud-Trace-Context": "37e49d37206663367d675c2ff01db8a2/15699104367477007142",
"Upgrade-Insecure-Requests": "1",
"Accept-Language": "en-US,en;q=0.9",
"X-IMForwards": "20",
"Host": "headers.jsontest.com",
"Referer": "http://www.jsontest.com/",
"Via": "1.1 ironport-s680.air-worldwide.com:80 (Cisco-WSA/9.0.1-162)",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
}
输出我想看到的内容(请打开链接): - http://headers.jsontest.com/
(False == 0) == True
答案 0 :(得分:1)
实际上,您确实获得了正确的HTTP响应。它只取决于你如何发送它(通过浏览器或来自Python的空请求)
当您通过浏览器打开它时,浏览器本身会添加其他标题。当您通过Python中的requests
发送请求时,不会发送这些标头。
HTTP响应只是镜像我们发送给它的标头。因此,如果您希望看到相同的响应,则必须使用requests
手动发送标头。
你可以像这样添加它们:
headers = {
"X-Cloud-Trace-Context": "37e49d37206663367d675c2ff01db8a2/15699104367477007142",
"Upgrade-Insecure-Requests": "1",
"Accept-Language": "en-US,en;q=0.9",
"X-IMForwards": "20",
"Host": "headers.jsontest.com",
"Referer": "http://www.jsontest.com/",
"Via": "1.1 ironport-s680.air-worldwide.com:80 (Cisco-WSA/9.0.1-162)",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
}
import requests
r = requests.get('http://headers.jsontest.com/', headers = headers)
print( r.json() )
返回:
{u'Via': u'1.1 ironport-s680.air-worldwide.com:80 (Cisco-WSA/9.0.1-162)', u'Acce
pt-Language': u'en-US,en;q=0.9', u'X-IMForwards': u'20', u'Accept': u'text/html,
application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', u'
Upgrade-Insecure-Requests': u'1', u'Host': u'headers.jsontest.com', u'Referer':
u'http://www.jsontest.com/', u'X-Cloud-Trace-Context': u'37e49d37206663367d675c2
ff01db8a2/14205897462093082399', u'User-Agent': u'Mozilla/5.0 (Windows NT 6.1; W
in64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/53
7.36'}