【问题标题】:fetch and save http response before redirect using mechanize在使用 mechanize 重定向之前获取并保存 http 响应
【发布时间】:2014-10-28 22:46:37
【问题描述】:

我正在尝试在 python 中获取示例页面

import mechanize
 def viewpage(url):
  browser = mechanize.Browser()
  page = browser.open(url)
  source_code = page.read()
  print source_code
viewpage('https://sama.com/index.php?req=1')

但是每次它都会被重定向到 index2.php(通过来自网络服务器的位置标头),因此例如代码打印来自 index2.php 而不是 index.php 的响应是否有避免这种情况?

【问题讨论】:

  • 你只是想抓取网页的源代码?
  • 是的,只是为了获取源代码。所以我可以解析它。

标签: python redirect mechanize


【解决方案1】:

您可以使用urllib2requests 处理更复杂的内容。

import urllib2

response = urllib2.urlopen("http://google.com")
page_source = response.read()

urllib2 是内置模块,requests 是第 3 方。

【讨论】:

  • 这是不正确的,因为 urllib2.urlopen 将跟随重定向。虽然我不希望这样的事情发生。
  • @SamaAzari,您示例中的网址不会重定向,我不想出去寻找网页。我只是不知道有什么想法。
猜你喜欢
  • 2011-02-10
  • 1970-01-01
  • 2021-11-23
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多