从网站中提取元数据

2022-01-18 00:00:00 regex metadata tags javascript html

我想知道 javascript 中是否有一种方法可以让我处理 html 源代码,从而可以取出我想要的特定标签?

I was wondering if there's a way in javascript that allows me to process the html source code that allows me to take out specific tags that I want?

对不起,如果这听起来很简单或太简单.我是编程新手.

Sorry if it sounds easy or too simple. i am new to programming.

推荐答案

如果你有一个字符串中的 HTML,那么你可以使用:

If you have the HTML in a string, then you can use:

var str = '<html></html>'; // your html text goes here
var div = document.createElement('div');
div.innerHTML = str;
var dom = div.firstChild; // dom is the object you want,
                          // you can manipulate it using standard dom methods

或者,使用 jQuery.jQuery 是一个帮助您更轻松地操作和访问 HTML 元素的库.首先,将其添加到文档的开头:

Alternately, use jQuery. jQuery is a library to help you manipulate and access HTML elements more easily. First, add this to the head of your document:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

这是对 jQuery 库的引用.然后,做:

This is a reference to the jQuery library. Then, do:

var foo = $("<html>Your html here</html>");

或者,如果您的 html 在变量中(例如 str),您可以这样做:

Or, if your html is in a variable (e.g. str), you can do:

var foo = $(str);

然后,您可以通过多种方式操作和解析 foo.例如,要删除所有段落元素,您可以使用

Then, you can manipulate and parse foo in a number of ways. For example, to remove all paragraph elements, you would use

foo.remove('p');

或者,要删除 id="bar" 的段落元素,请使用:

Or, to remove the paragraph element with id="bar", use:

foo.remove('p.bar');

完成修改后,您可以使用以下命令获取新的 html 文本:

Once you are done your modifications, you can get the new html text using:

foo.html();

为什么你的 html 是一个字符串?不是当前页面的html吗?

Why is your html in a string? Is it not the html of the current page?

相关文章