splash:select()方法与select_all()

版权声明:凡由本人原创,如有转载请注明出处https://me.csdn.net/qq_41424519,谢谢合作 https://blog.csdn.net/qq_41424519/article/details/87012878

select()

该方法可以选中符合条件的第一个节点,如果有多个节点符合条件,则只会返回一个,其参数是CSS选择器。示例如下:

1

2

3

4

5

6

7

function main(splash)

splash:go("https://www.baidu.com/")

input = splash:select("#kw")

input:send_text('Splash')

splash:wait(3)

return splash:png()

end

这里我们首先访问了百度,然后选中了搜索框,随后调用了send_text()方法填写了文本,然后返回网页截图。

结果如图7-15所示,可以看到,我们成功填写了输入框。

select_all()

此方法可以选中所有符合条件的节点,其参数是CSS选择器。示例如下:

1

2

3

4

5

6

7

8

9

10

11

function main(splash)

local treat = require('treat')

assert(splash:go("http://quotes.toscrape.com/"))

assert(splash:wait(0.5))

local texts = splash:select_all('.quote .text')

local results = {}

for index, text in ipairs(texts) do

results[index] = text.node.innerHTML

end

return treat.as_array(results)

end

这里我们通过CSS选择器选中了节点的正文内容,随后遍历了所有节点,将其中的文本获取下来。

运行结果如下:

1

2

3

4

5

6

7

8

9

10

11

Splash Response: Array[10]

0: "“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”"

1: "“It is our choices, Harry, that show what we truly are, far more than our abilities.”"

2: “There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”

3: "“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”"

4: "“Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”"

5: "“Try not to become a man of success. Rather become a man of value.”"

6: "“It is better to be hated for what you are than to be loved for what you are not.”"

7: "“I have not failed. I've just found 10,000 ways that won't work.”"

8: "“A woman is like a tea bag; you never know how strong it is until it's in hot water.”"

9: "“A day without sunshine is like, you know, night.”"

可以发现,我们成功地将10个节点的正文内容获取了下来。

猜你喜欢

转载自blog.csdn.net/qq_41424519/article/details/87012878