python sys.stdout.write() 重定向

2 投票
2 回答
510 浏览
提问于 2025-04-17 12:08

我正在把一个代理服务器重定向到我的脚本,这个脚本会检查网址、用户代理等信息,然后根据这些检查结果把用户引导到指定的网址。

现在,如果我向客户端发送一个GET请求,它是可以工作的,但显示的只是网站的文本版本,没有任何CSS样式或图片。这是发送请求回客户端的代码的一部分……

if l.startswith('User-Agent:') and ('Safari' in l):

    new = "http://www.yahoo.com"
    new_get = "GET" + " " + str(new) + " " + "HTTP/1.1" + "Status: 302" + "\r\n\r\n"
    sys.stdout.write(new_get)
    sys.stdout.flush()

我尝试设置了

new = "302:http://www.yahoo.com"

但也没有效果……

有没有什么想法呢??

更新:

if l.startswith('User-Agent:') and ('Safari' in l):

    new = "http://www.yahoo.com"
    new_get = "GET" + " " + str(new) + " " + "HTTP/1.1" + "Status: 302" + "\r\n\r\n"
    uopen = urllib2.urlopen("http://www.yahoo.com")
    sys.stdout.write(uopen.read())
    sys.stdout.flush()

我尝试使用urllib2,但浏览器渲染页面需要很长时间……结果还是一样,没有图片和CSS……

2 个回答

-1

你为什么要手动做这些事情呢?Python的标准库里有一些模块,比如urllib2httplib,甚至还有SimpleHTTPServer,可以帮助你完成这些任务。

0

如果你想把用户引导到另一个地方:

new_url = 'http://www.yahoo.com/'

print 'Status:', '302 Found'
print 'Location:', new_url
print

如果你想直接给用户提供某些内容:

from shutil import copyfileobj
from sys import stdout
from urllib2 import urlopen

http_message = urlopen("http://www.yahoo.com")
copyfileobj(http_message, stdout)

撰写回答