5

これまでのところ、次の作品があります。

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)

これは、接続が完全に確立されたことを意味します。url's今、私はこれを使って自分のタイトルを取得したいと思いsocket.httpます。以前の SO の質問とluasocket の http ドキュメントを検索しました。しかし、ページの全体/一部を変数にフェッチ/保存し、それを使って何かをする方法についてはまだわかりません。

助けてください。

4

1 に答える 1

4

「ジェネリック」形式の http.request() を使用しています。これには、LTN12 シンクを介して本文を保存する必要があります。思ったほど複雑ではありません。次のコードを試してください。

local socket = require "socket.http"
local ltn12 = require "ltn12"; -- LTN12 lib provided by LuaSocket

-- This table will store the body (possibly in multiple chunks):
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>"
}
-- Join the chunks together into a string:
local result = table.concat(result_table);
-- Hacky solution to extract the title:
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-25T02:43:58.133 に答える