如何在shell变量中获取网页的内容?

时间:2010-09-18 18:44:42

标签: linux bash shell wget

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

7 个答案:

答案 0 :(得分:167)

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

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

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

您可以使用curl命令以及:

-q

我们需要使用content=$(curl -L google.com) echo $content 选项,因为我们请求的页面可能已移动。在这种情况下,我们需要从新位置获取页面。 -L-L选项可帮助我们解决此问题。

答案 1 :(得分:21)

有很多方法可以从命令行获取页面...但它还取决于您是否需要代码源或页面本身:

如果您需要代码来源:

卷曲:

curl $url

使用wget:

wget -O - $url

但是如果你想通过浏览器看到你可以看到的内容,lynx可能很有用:

lynx -dump $url

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

祝你好运:)

答案 2 :(得分:9)

wget命令或curl

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


资源:

答案 3 :(得分:3)

content=`wget -O - $url`

答案 4 :(得分:2)

您可以使用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.

答案 5 :(得分:2)

如果您安装了LWP,则会提供名为“GET”的二进制文件。

$ GET http://example.com
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
  <META http-equiv="Content-Type" content="text/html; charset=utf-8">
  <TITLE>Example Web Page</TITLE>
</HEAD> 
<body>  
<p>You have reached this web page by typing &quot;example.com&quot;,
&quot;example.net&quot;,&quot;example.org&quot
  or &quot;example.edu&quot; into your web browser.</p>
<p>These domain names are reserved for use in documentation and are not available 
  for registration. See <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC 
  2606</a>, Section 3.</p>
</BODY>
</HTML>

wget -O-curllynx -source行为相似。

答案 6 :(得分:1)

没有 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
相关问题