【发布时间】:2017-10-07 14:25:32
【问题描述】:
模块 Requests 返回的 HTTP 标头有问题。
我正在使用以下代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
response = requests.get("http://www.google.co.il",proxies={'http': '','https':''})
data = response.text
# response.text returns the appropriate html code
# (<!doctype html><html dir="rtl" itemscope=""....)
if response.status_code == requests.codes.ok:
# How do I send those headers to the conn (browser)
print "HEADERS: " + str(response.headers)
conn.send(data)
我正在尝试向 www.google.co.il 发送 GET 请求,并将响应发送到浏览器(在示例中我称之为“conn”)。问题是浏览器不会显示收到的 HTML 代码,而是收到 ERR_EMPTY_RESPONSE。 响应中的标头是:
HEADERS: {'Content-Length': '5451', 'X-XSS-Protection': '1; mode=block', 'Content-Encoding': 'gzip', 'Set-Cookie': 'NID=103=RJzu4RTCNxkh-75dvKBHx-_jen9M8iPes_AdOIQqzBVZ0VPTz1PlQaAVLpwYOmxZlTKmcogiDb1VoY__Es0HqSNwlkmHl3SuBZC8_8XUfqh1PzdWTjrXRnB4S738M1lm; expires=Wed, 08-Nov-2017 10:05:46 GMT; path=/; domain=.google.co.il; HttpOnly', 'Expires': '-1', 'Server': 'gws', 'Cache-Control': 'private, max-age=0', 'Date': 'Tue, 09 May 2017 10:05:46 GMT', 'P3P': 'CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."', 'Content-Type': 'text/html; charset=windows-1255', 'X-Frame-Options': 'SAMEORIGIN'}
有人告诉我问题是我没有向浏览器发送任何标题。这真的是问题吗?还有其他建议吗?如果是问题,我如何将适当的标头发送到浏览器?
编辑:我忘了提到连接是 通过代理服务器。
任何帮助都会很棒!
非常感谢,Yahli。
【问题讨论】:
-
conn是什么?插座? -
是的,
conn是一个套接字。 -
有点像拦截代理对吗?您必须向浏览器发送完整的 HTTP 响应,而不仅仅是正文。如果您使用的是 sockets ,您可以跳过
requests并使用socket发送 HTTP 请求。如果您坚持使用requests,则必须从response对象构造标题。 -
@t.m.adam 介意用这些方法写一个答案吗?因为我不知道如何使用
socket发送 http 请求或从响应中构建标头。 -
好的,等一下
标签: python http http-headers python-requests response