使用LuaSocket和代理获取URL的页面。

到目前为止,我有以下代码片段:

local socket = require "socket.http"
client,r,c,h = socket.request{url = "http://example.com/", proxy="<my proxy and port here>"}
for i,v in pairs( c ) do
  print( i, v )
end

这将给我一个如下的输出:

connection  close
content-type    text/html; charset=UTF-8
location    http://www.iana.org/domains/example/
vary    Accept-Encoding
date    Tue, 24 Apr 2012 21:43:19 GMT
last-modified   Wed, 09 Feb 2011 17:13:15 GMT
transfer-encoding   chunked
server  Apache/2.2.3 (CentOS)

这意味着连接已经建立得 完美。现在,我想使用这个 socket.http 抓取我的 url's 标题。我搜索了之前的 SO 问题和 luasocket 的 http 文档。但是,我仍然不知道如何将整个/部分页面存储在一个变量中并对其进行处理。

请帮帮我。

原文链接 https://stackoverflow.com/questions/10306489

点赞
stackoverflow用户15996
stackoverflow用户15996

你正在使用'http.request()'的“通用”形式,该形式需要通过LTN12 sink存储主体。 尝试以下代码:

local socket = require "socket.http"
local ltn12 = require "ltn12"; -- 由 LuaSocket 提供的 LTN12 库

-- 此表将存储主体(可能分为多个块):
local result_table = {};
client,r,c,h = socket.request{
    url = "http://example.com/",
    sink = ltn12.sink.table(result_table),
    proxy="<my proxy and port here>"
}
-- 将块连接成字符串:
local result = table.concat(result_table);
-- 提取标题的笨方法:
local title = result:match("<[Tt][Ii][Tt][Ll][Ee]>([^<]*)<");
print(title);

如果您的代理在应用程序中保持不变,则更简单的解决方法是使用 http.request() 的简单形式,并通过 http.PROXY 指定代理:

local http = require "socket.http"
http.PROXY="<my proxy and port here>"

local result = http.request("http://www.youtube.com/watch?v=_eT40eV7OiI")
local title = result:match("<[Tt][Ii][Tt][Ll][Ee]>([^<]*)<");
print(title);

输出:

    Flanders and Swann - A song of the weather
  - YouTube
2012-04-25 02:43:58