2012-04-24 2 views
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) 

完全に。今、このsocket.httpを使用して私のurl'sのタイトルを取得したいと思います。以前のSOの質問とluasocket's http documentationを検索しました。しかし、私はまだ変数のページの全体/一部をフェッチ/格納し、それを使って何かをする方法についてはまだ考えていません。

助けてください。

答えて

4

「generic」形式のhttp.request()を使用していますが、LTN12シンクを介して本体を格納する必要があります。それは思ったほど複雑ではないですが、このコードを試してください:あなたのプロキシがアプリケーション全体で一定である場合)、より簡単な解決策はhttp.requestの簡単なフォームを(使用することです

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.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 
+0

ありがとう!これは一般的にあらゆる種類のページでうまく機能します。 :)しかし、YouTubeのリンクのタイトルを取得しようとすると、 'result'変数には[** 404 error **](http://www.hastebin.com/gikavorone.xml)のページしかありません。私は両方の方法を試みました。もう1つはページをより早く取得します。 :) – hjpotter92

+0

私はちょうど例のYouTubeリンクと私が得る出力で更新しました。それはすべて私のためにうまくいく。タイトルには空白が埋め込まれていて、たぶんHTMLエンティティもあります。おそらく、それらをストリッピングして変換することによって少し正規化したいでしょう。 – MattJ

+0

いいえ、まだ動作しませんでした。私はSciTeで(02.luaという名前の)ファイルを実行しています。ここでは、出力とコードのスクリーンショット(私は4つの異なるWebページを使用しました.2つは自分のWebサーバー上にあります)。確認:http://i.stack.imgur.com/XkQQj.jpg – hjpotter92