wwzlhx

13.获取网页中各对象的标题和链接

在网页属性控制台获取百度搜索出来的所有数量可使用:

document.querySelectorAll("h3")

其中h3是标题元素的标签,注意此命令返回的是一个数组

 

取第4个标题的标题名:

document.querySelectorAll("h3")[3].textContent

 

取第4个标题的连接:

document.querySelectorAll("h3")[3].querySelector("a").href

a为标题的连接标签

 

循环取出各标题和链接:

for (var i=0;i<document.querySelectorAll("h3").length;i++){标题=document.querySelectorAll("h3")[i].textContent;链接=document.querySelectorAll("h3")[i].querySelector("a").href;console.log(标题);console.log(链接)}

其中i微循环次数。“标题”和“链接”是两个变量

document.querySelectorAll("h3").length:取数组成员数

i++:每次加1

console.log():控制台输出

 

将结果输出到一个数组中:

第一步定义一个空数组:

var 数组=[]

第二步循环取出标题和链接并写入数组中:

for (var i=0;i<document.querySelectorAll("h3").length;i++){标题=document.querySelectorAll("h3")[i].textContent;链接=document.querySelectorAll("h3")[i].querySelector("a").href;console.log(标题);console.log(链接);数组.push([标题,链接])}

其中“数组.push([标题,链接])”意思是将“标题”“链接”写入定义的数组变量“数组”中.

 

第三步输出数组变量“数组”:

数组

 

如果将结果在Uibot中执行则代码为:

function(){var 数组=[];for (var i=0;i<document.querySelectorAll("h3").length;i++){标题=document.querySelectorAll("h3")[i].textContent;链接=document.querySelectorAll("h3")[i].querySelector("a").href;数组.push([标题,链接])}

;return 数组}

其中:var 数组=[]表示定义空数组;注意去掉了控制台输出

此结果是字符串,要想变为数组,则需要命令“将JSON转换为JSON对象”来转成数组.

如果想过滤出某些不同的元素,在网页控制台可这样写:(例子是在百度搜索“Uibot”时想过滤掉广告)

 

document.querySelectorAll("h3[class='c-title t t tts-title'],[class='c-title t'],[class='t c-line-clamp1'],div[class='vmp-project-new_1F7Ig']")

可利用h3、div等来过滤

如果想输出得到结果的标题:Uibot的代码为:

function(){var 数组=[];for (var i=0;i<document.querySelectorAll("h3[class='c-title t t tts-title'],[class='c-title t'],[class='t c-line-clamp1'],div[class='vmp-project-new_1F7Ig']").length;i++){标题=document.querySelectorAll("h3[class='c-title t t tts-title'],[class='c-title t'],[class='t c-line-clamp1'],div[class='vmp-project-new_1F7Ig']")[i].textContent;数组.push([标题])};return 数组}

posted on 2022-09-29 15:58  轵城  阅读(231)  评论(0)    收藏  举报

导航