简体   繁体   English

如何使用JavaScript抓取页面中的所有链接

[英]How to scrape all links in a page with javascript

I am trying to write a chrome extension to change all hrefs in a page using this code 我正在尝试编写一个Chrome扩展程序以使用此代码更改页面中的所有href

var a = document.querySelector("a[href]");
a.href = "http://www.google.com";

But this code only fetches the first href but only if it is not embedded in another attribute(If the term is wrong I am meaning div, p, h etc.) 但是此代码仅获取第一个href,但前提是未将其嵌入另一个属性(如果该术语错误,则表示div,p,h等)。

Could someone show me how to fetch all hrefs no matter what? 有人可以告诉我如何获取所有href吗?

document.querySelector only returns the first element within the document, and so in this case you will want to use document.querySelectorAll which instead returns a list of all matching elements. document.querySelector只返回文档中的第一个元素,因此在这种情况下,您将要使用document.querySelectorAll ,它返回所有匹配元素的列表。

var elements = document.querySelectorAll('a');

for (var i = 0; i < elements.length; i++) {
  elements[i].href = 'http://google.com';
}

but only if it is not embedded in another attribute(If the term is wrong I am meaning div, p, h etc.) 但仅当它未嵌入另一个属性中时(如果该术语错误,我的意思是div,p,h等)

I believe you are talking about tags instead of attributes. 我相信您是在谈论标签而不是属性。 To select all tags with the present of the href attribute, do this: 要选择所有带有href属性的标签,请执行以下操作:

var list = document.querySelectorAll("*[href]");
for(var i = 0; i < list.length; i++){
    list[i].href = "http://www.google.com";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM