简体   繁体   中英

Can I scrapping an HTML code snippet on browser

I have an HTML code block. How can I scrapping on browser this snippet with pure JS or 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. 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. 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. 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.

 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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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