Understanding LUA urlGet and RegEx



在一个项目中工作,对urlGet没有什么经验,也没有找到一个很好的参考资料和例子让我自己完成这项工作,所以希望这里的社区能帮助我。

我正试图从网页中提取一些数据,特别是:

https://rrtp.comed.com/rrtp/ServletFeed?type=instanthourly

本页为我们这些参加名为"住宅实时定价"项目的人提供了电力的实时定价数据。我希望从这个页面中提取数字成本数据,用于家庭自动化系统。

我使用另一个类似的驱动程序作为我工作的基本示例,但它不是一个直接的翻译,因为我们通过Yahoo weather API获取数据的示例。然而,据我所知,总的原则应该是一样的。以下是示例代码中的相关片段,特别是RequestData函数和ParseData部分:

function Init()
-- Create Variables
for k, v in pairs(weatherData) do
if (not Variables[k]) then
C4:AddVariable(k, v, "NUMBER", true, false)
end
end
end
function RequestData()
local query = "select%20wind%2C%20atmosphere%2C%20item.title%2C%20item.condition.code%2C%20item.condition.temp%20from%20weather.forecast%20where%20woeid%3D" .. Properties[WOEID] .. "%20and%20u%3D%22" .. Properties[UNIT] .. "%22"
C4:urlGet(string.format("http://query.yahooapis.com/v1/public/yql?q=%s", query))
end
function ReceivedAsync(ticketId, strData, responseCode, tHeaders)
dbg(string.format("ReceivedAsync[%s]: %s", ticketId, strData))
for k, v in pairs(weatherData) do
local tempVal = ParseData(strData, k)
-- Set property, table, and variable
Properties[displayProperties[k]] = tempVal
weatherData[k] = tempVal
C4:SetVariable(k, tostring(tempVal))
OnPropertyChanged(displayProperties[k])
if (tempVal ~= weatherData[k]) then
if (k == RISING) then
tempVal = weatherRising[tonumber(tempVal)] or "N/A"
end
end
C4:UpdateProperty(displayProperties[k], tostring(tempVal))
end
if(weatherData["code"] ~= "N/A" and weatherData["code"] ~= nil) then
weatherData["condition"] = weatherConditions[tonumber(weatherData["code"])]
C4:UpdateProperty(CONDITION, weatherData["condition"])
end
for k, v in pairs(weatherData) do
dbg(displayProperties[k] .. ":" .. v)
end
end
function ParseData(strData, item)
return string.match(strData, string.format("%s="(.-)"", item)) or 
string.match(strData, string.format("<%s>Conditions for (.+)</%s>", item, item)) or
"N/A"
end

所以。。。

我的第一个问题,我想我知道答案,是当你使用urlGet时,它是如何看待网页的?也就是说,它是将其视为原始HTML还是不包含所有HTML标记。

我问这个问题是因为我相信它改变了我需要构建的正则表达式来提取数字数据。

这是我提议的urlGet和字符串匹配。如果我的方向正确与否,以及任何其他意见,我将不胜感激。

function RequestData()
C4:urlGet(string.format("https://rrtp.comed.com/rrtp/ServletFeed type=instanthourly))
end

function ParseData(strData, item)
return string.match(strData, string.format("b([0-9].[0-9])b")) or
"N/A"
end

尝试此模式提取价格:"(%d+%.%d+)"。请注意,Lua模式中的转义是%

最新更新