【问题标题】:curl 302 redirect not working (command line)curl 302 重定向不起作用(命令行)
【发布时间】:2014-01-03 13:53:43
【问题描述】:

在浏览器中,导航到此 URL 会启动一个 302(临时移动)请求,该请求又会下载文件。

http://www.targetsite.com/target.php/?event=download&task_id=123

当我通过 Chrome 网络工具查看实际发生的情况时,我看到重定向将转到动态生成的路径,该路径在下载后立即取消。换句话说,即使我知道完整路径,我也没有时间手动调用它。

那么,如何使用命令行来模拟浏览器的操作呢?

我试过了

curl --cookies bin/cookies.txt -O -L "http://www.targetsite.com/target.php/?event=download&task_id=123" --compressed

但这只会返回乱码。这样做的目的是以编程方式下载此文件,而无需导航到该站点。不幸的是,我无法在此处共享该站点,因为它需要登录。

【问题讨论】:

    标签: bash curl scrape


    【解决方案1】:

    您需要提供-L--location 选项以启用curl 以遵循HTTP 重定向。

    引用man curl:

       -L, --location
              (HTTP/HTTPS)  If  the server reports that the requested page has
              moved to a different location (indicated with a Location: header
              and  a  3XX  response code), this option will make curl redo the
              request on the new place. If used together with -i, --include or
              -I, --head, headers from all requested pages will be shown. When
              authentication is used, curl only sends its credentials  to  the
              initial  host.  If a redirect takes curl to a different host, it
              won't be able to intercept the user+password. See  also  --loca‐
              tion-trusted  on how to change this. You can limit the amount of
              redirects to follow by using the --max-redirs option.
    
              When curl follows a redirect and the request is not a plain  GET
              (for example POST or PUT), it will do the following request with
              a GET if the HTTP response was 301, 302, or 303. If the response
              code  was  any  other  3xx code, curl will re-send the following
              request using the same unmodified method.
    

    【讨论】:

    • 我很抱歉。 -L 是我尝试过的选项,而不是 -R (我在上面更正了)。它似乎只是返回乱码(字面意思是非 ascii 奇怪的字符)。
    • @user2029890 您是否尝试省略--compressed 选项以查看它是否有任何效果?
    • @user2029890 你看到--location-trusted 选项了吗?
    • 问题已解决。我只需要构造 curl --cookie /bin/cookies.txt -L -o foo-dev.zip "targetsite.com/target.php/?event=download&task_id=123" 之类的命令。感谢您的所有帮助
    • 仅供参考,但您看到的“乱码”很可能是自动下载的文件内容。如果您不指定-o <filename>,它只会为您提供转储到控制台的响应数据。您可以使用<curl stuff> > output.file 将该数据重定向到一个文件中,也可以像现在一样使用-o 参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    相关资源
    最近更新 更多