class sss(webapp.RequestHandler):
  def get(self):
    url = "http://www.google.com/"
    result = urlfetch.fetch(url)    
    if result.status_code == 200:
        self.response.out.write(result.content)

当我更改代码时:

if result.status_code == 200:
        self.response.out.write(result.content.decode('utf-8').encode('gb2312'))

它显示出奇怪的东西。我该怎么办?

当我使用它时:

self.response.out.write(result.content.decode('big5'))

该页面与我看到的Google.com不同。

如何获得我看到的Google.com?

有帮助吗?

解决方案

Google可能正在为您提供ISO-8859-1。至少,这就是他们为我服务的用户代理“ appengine-google;(+)http://code.google.com/appengine)“(urlfetch使用)。内容类型的标题值为:

text/html; charset=ISO-8859-1

因此,您将使用:

result.content.decode('ISO-8859-1')

如果您检查 result.headers["Content-Type"], ,您的代码可以适应另一端的更改。通常,您可以将CHAR集(在这种情况下为ISO-8859-1)直接传递到Python解码方法。

其他提示

如何获得我看到的Google.com?

您可能不会将相对的URL与图像,JavaScript,CSS等使用,因此您不会将绝对URL变成Google的网站。要确认这一点:您的日志应显示404个错误(“未找到”)作为您服务的浏览器“ Just html”尝试找到您不提供的相对添加的资源。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top