我正在使用谷歌应用程序引擎来获取提要 url,但很少有 url 是 301 重定向我想获得最终的 url,它返回给我结果
我正在使用通用提要阅读器来解析 url 是否有任何方法或任何功能可以给我最终的 url。
我正在使用谷歌应用程序引擎来获取提要 url,但很少有 url 是 301 重定向我想获得最终的 url,它返回给我结果
我正在使用通用提要阅读器来解析 url 是否有任何方法或任何功能可以给我最终的 url。
If you're using the urlfetch API, you can just access the final_url
attribute of the response object you get from urlfetch.fetch()
, assuming you set follow_redirects
to True
:
>>> from google.appengine.api import urlfetch
>>> url_that_redirects = 'http://www.example.com/redirect/'
>>> resp = urlfetch.fetch(url=url_that_redirects, follow_redirects=False)
>>> resp.status_code
302 # or 301 or whatever
>>> resp = urlfetch.fetch(url=url_that_redirects, follow_redirects=True)
>>> resp.status_code
200
>>> resp.final_url
'http://www.example.com/final_url/'
Note that the follow_redirects
keyword argument defaults to True
, so you don't have to set it explicitly.
无法通过解析获得“最终”URL,为了解析它,您至少需要执行 HTTP HEAD 操作
您可以通过手动处理重定向来做到这一点。调用 fetch 时,传入follow_redirects=False
. 如果您的响应对象的 HTTP 状态是重定向代码(301 或 302),请抓取Location
响应标头并再次获取,直到 HTTP 状态变为其他状态。添加完整性检查(可能最多 5 个重定向)以避免重定向循环。