简体   繁体   English

我可以在浏览器上删除 HTML 代码片段吗

[英]Can I scrapping an HTML code snippet on browser

I have an HTML code block.我有一个 HTML 代码块。 How can I scrapping on browser this snippet with pure JS or JQuery?我怎样才能在浏览器上用纯 JS 或 JQuery 删除这个片段?

Here is my code:这是我的代码:

<ul>
    <li>New York</li>
    <li>London</li>
    <li>Madrid</li>
    <li>Paris</li>
</ul>

The result I expected is:我预期的结果是:

<p>New York, London, Madrid, Paris</p>

I don't need to get a website's HTML document.我不需要获取网站的 HTML 文档。 I already have many blocks.我已经有很多积木了。 I just want to client-side scrap these blocks.我只想在客户端废弃这些块。

If I understood you correctly you already have a string containing the HTML so the only thing you need is to parse that string.如果我理解正确的话,您已经有一个包含 HTML 的string ,所以您唯一需要做的就是解析该字符串。 This can be done using the DOMParser class. From then on it's straightforward because you get a Document returned which offers all the methods you should already now from the DOM of a webpage.这可以使用DOMParser class 来完成。从那时起它就很简单了,因为你得到一个返回的Document ,它提供了你现在应该从网页的 DOM 中获得的所有方法。 In this case you can use getElementsByTagName() to get all the list items and then use map() to only get the textContent those list items.在这种情况下,您可以使用getElementsByTagName()获取所有列表项,然后使用map()仅获取那些列表项的textContent

 const domParser = new DOMParser(); const parsed = domParser.parseFromString(` <ul> <li>New York</li> <li>London</li> <li>Madrid</li> <li>Paris</li> </ul>`, "text/html"); const cityArray = [...parsed.getElementsByTagName("li")].map(li => li.textContent); console.log(cityArray);

Edit编辑

Now that I am reading your edited question I think what you want to do has nothing to do with web scraping you just want to edit your existing DOM on the website you have.既然我正在阅读您编辑过的问题,我认为您想要做的与 web 抓取无关,您只想在您拥有的网站上编辑现有的 DOM。

In that case you can skip the whole parsing and instead do this:在这种情况下,您可以跳过整个解析,而是执行以下操作:

 const cityArray = [...document.getElementsByTagName("li")].map(li => li.textContent); const pTag = document.createElement("p"); pTag.textContent = cityArray.join(", "); document.body.appendChild(pTag);
 <ul> <li>New York</li> <li>London</li> <li>Madrid</li> <li>Paris</li> </ul>

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

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