【问题标题】:How to get the contents of a webpage in a shell variable?如何在 shell 变量中获取网页的内容?
【发布时间】:2010-09-18 18:44:42
【问题描述】:

在 Linux 中,如何获取 URL 并在 shell 脚本的变量中获取其内容?

【问题讨论】:

    标签: linux bash shell wget


    【解决方案1】:

    您可以使用wget 命令下载页面并将其读入变量中:

    content=$(wget google.com -q -O -)
    echo $content
    

    我们使用wget-O 选项,它允许我们指定wget 转储页面内容的文件的名称。我们指定- 将转储到标准输出并将其收集到变量content 中。您可以添加-q quiet 选项来关闭 wget 输出。

    您可以为此使用curl 命令以及:

    content=$(curl -L google.com)
    echo $content
    

    我们需要使用-L 选项,因为我们请求的页面可能已经移动。在这种情况下,我们需要从新位置获取页面。 -L--location 选项可以帮助我们解决这个问题。

    【讨论】:

    • 这是一个非常巧妙的技巧。我通过代理服务器上的 php 脚本调用 shell 脚本。当被询问时,代理服务器会打开昂贵的服务器,这些服务器会在 2 小时后自行关闭。我需要来自 wget 的输出作为标准输出来反馈到 Jenkins 控制台记录。
    • 我还没有得到这个......任何人都可以演示如何,例如。在此链接的变量中获取 img 标签 www2.watchop.io/manga2/read/one-piece/1/4 ??
    • @juggernaut1996:这应该是一个单独的问题。简而言之,您必须下载页面,提取正确元素的src 属性,然后下载那个页面。如果你安装了tq,这个命令应该可以做到:curl -s http://ww1.watchop.io/manga2/read/one-piece/1/4 | tq -j -a src "#imgholder a img" | xargs wget
    • Wget 1.14 版本不接受 convert_links = on-O- 选项。它失败并出现错误-k can be used together with -O only if outputting to a regular file.。是预期的吗?
    【解决方案2】:

    从命令行获取页面的方法有很多种……但这也取决于您需要代码源还是页面本身:

    如需代码源:

    卷曲:

    curl $url
    

    使用 wget:

    wget -O - $url
    

    但如果您想获得通过浏览器可以看到的内容,lynx 会很有用:

    lynx -dump $url
    

    我认为你可以为这个小问题找到很多解决方案,也许你应该阅读这些命令的所有手册页。并且不要忘记用您的 URL 替换 $url :)

    祝你好运:)

    【讨论】:

    • 如果我是你,我会用双引号引起来。
    【解决方案3】:

    wget 命令或curl

    您现在可以使用 wget 下载的文件。或者您可以使用 curl 处理流。


    资源:

    【讨论】:

      【解决方案4】:
      content=`wget -O - $url`
      

      【讨论】:

      • @rjack:(但您链接到的文章确实为 $(...) 语法提供了一个很好的案例。)
      【解决方案5】:

      您可以使用curlwget 来检索原始数据,或者您可以使用w3m -dump 来获得网页的精美文本表示。

      $ foo=$(w3m -dump http://www.example.com/); echo $foo
      You have reached this web page by typing "example.com", "example.net","example.org" or "example.edu" into your web browser. These domain names are reserved for use in documentation and are not available for registration. See RFC 2606, Section 3.
      

      【讨论】:

        【解决方案6】:
        【解决方案7】:

        没有 curl,没有 wget,没有 ncat,什么都没有?使用telnet

        $ content=$(telnet localhost 80)
        GET / HTTP/1.1
        Host: localhost
        Connection: close
         
        Connection closed by foreign host.
        

        $ echo $content
        HTTP/1.1 200 OK Date: Mon, 22 Mar 2021 12:45:02 GMT Server:
        Apache/2.4.46 (Fedora) OpenSSL/1.1.1j Last-Modified: Mon, 31 Dec 2018
        15:56:45 GMT ETag: "a4-57e5375ad21bd" Accept-Ranges: bytes
        Content-Length: 164 Connection: close Content-Type: text/html;
        charset=UTF-8 Success! 192.168.1.1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-06
          • 1970-01-01
          • 2017-10-22
          • 2016-12-07
          • 2011-06-24
          • 2011-07-15
          • 1970-01-01
          • 2011-05-29
          相关资源
          最近更新 更多