0

我正在尝试加载一个 url,但我收到了这个错误:

DownloadError: ApplicationError: 2 重复重定向太多

这是我正在使用的代码:

  headers = { 'User-Agent' : 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1' }    
  url = "http://www.cafebonappetit.com/menu/your-cafe/collins-cmc/cafes/details/50/collins-bistro"
  cmcHTM = urlfetch.fetch(url=url)
  cmcHTML = str(cmcHTM.content)

我检查了这个网站的重定向:http: //www.internetofficer.com/seo-tool/redirect-check/ ,我发现这个网站被重定向到它自己!所以 url fetch 似乎在试图加载这个页面。同时,这个页面在我的浏览器中加载得很好。

所以我尝试使用这段代码:

  cmcHTM = urlfetch.fetch(url=url,
    follow_redirects=False,
    deadline=100
    )

但这只是什么都不返回。有没有办法得到这个html?!

4

2 回答 2

3

回复较晚,抱歉。我发现这行得通:

import urllib, urllib2, Cookie
from google.appengine.api import urlfetch

class URLOpener:
  def __init__(self):
      self.cookie = Cookie.SimpleCookie()

  def open(self, url, data = None):
      if data is None:
          method = urlfetch.GET
      else:
          method = urlfetch.POST

      while url is not None:
          response = urlfetch.fetch(url=url,
                          payload=data,
                          method=method,
                          headers=self._getHeaders(self.cookie),
                          allow_truncated=False,
                          follow_redirects=False,
                          deadline=10
                          )
          data = None # Next request will be a get, so no need to send the data again. 
          method = urlfetch.GET
          self.cookie.load(response.headers.get('set-cookie', '')) # Load the cookies from the response
          url = response.headers.get('location')

      return response

  def _getHeaders(self, cookie):
      headers = {
                 'Host' : 'www.google.com',
                 'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)',
                 'Cookie' : self._makeCookieHeader(cookie)
                  }
      return headers

  def _makeCookieHeader(self, cookie):
      cookieHeader = ""
      for value in cookie.values():
          cookieHeader += "%s=%s; " % (value.key, value.value)
      return cookieHeader

我猜关键是 while 循环 - 根据返回标头进行重定向......

于 2013-01-04T20:11:14.683 回答
1

我认为这是站点中的问题,而不是您的代码中的问题。该站点似乎经过精心设计,因此当它未检测到通常由浏览器发送的某些标头时,它会重定向到自身。例如,当我尝试使用 curl 访问它时,我得到一个带有 302 重定向到自身的空正文,但在浏览器中我得到一个页面。您必须询问网站所有者他们正在检查什么......

于 2012-02-22T00:46:41.927 回答