套接字 – 使用luasocket和proxy获取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的标题.我搜索了之前的SO问题和luasocket’s http documentation.但是,我仍然不知道如何在变量中获取/存储整个/部分页面并使用它做一些事情.

请帮忙.

解决方法

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

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...