【问题标题】:Fetching page of url using luasocket and proxy使用 luasocket 和代理获取 url 页面
【发布时间】:2012-05-05 14:18:22
【问题描述】:

到目前为止,我有以下一块:

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。但是,我仍然不知道如何在变量中获取/存储整个/部分页面并对其进行处理。

请帮忙。

【问题讨论】:

    标签: sockets lua fetch luasocket


    【解决方案1】:

    您正在使用 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
    

    【讨论】:

    • 谢谢!这通常适用于各种页面。 :) 但是,在尝试获取 youtube 链接的标题时,result 变量中只有 404 error 页面。我尝试了这两种方法。第二个更快地获取页面。 :)
    • 我刚刚更新了一个示例 YouTube 链接和我得到的输出。这一切对我来说都很好。标题有空格填充,有时也可能是 HTML 实体。您可能希望通过剥离和转换它们来对其进行标准化。
    • 不,还没有工作。我正在 SciTe 中运行文件(名为 02.lua)。这是输出和代码的屏幕截图(我使用了 4 个不同的网页,2 个在我自己的网络服务器上)。检查:i.stack.imgur.com/XkQQj.jpg
    • 有趣。我只能猜测这与您的代理有关,因为这是您的代码和我的代码之间的唯一区别。为了调试这样的东西,我通常会使用 Wireshark,并记录请求和响应以查看是否有任何意外。您是说它适用于某些页面,但不是全部?
    • 这是另一个带有一些网站示例的屏幕截图。 i.stack.imgur.com/SC7jw.jpg 如您所见,youtube.com 被重定向到 google 并且 stackoverflow 甚至没有被打开,除此之外,luasocket 的官方页面返回 404 错误.
    猜你喜欢
    • 1970-01-01
    • 2011-11-14
    • 2020-03-07
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 2020-12-15
    • 2018-08-29
    • 1970-01-01
    相关资源
    最近更新 更多