网页爬虫 - 如何用javascript解析html判断该元素最后有没有加上 / >
本文介绍了网页爬虫 - 如何用javascript解析html判断该元素最后有没有加上 / >的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
希望能够利用javascript解析html字串,判断所有的<img>元素,如果结尾有加上/>,就像是<img />的话,就删除。
假设现在有一组字串:
<h1>h1</h1>
<img id="a" src="https://placehold.it/200x200" alt="" />
<h2>h2</h2>
<img id="b" src="https://placehold.it/200x200" alt="">
希望能够改为
<h1>h1</h1>
<img id="a" src="https://placehold.it/200x200" alt="">
<h2>h2</h2>
<img id="b" src="https://placehold.it/200x200" alt="">
我尝试使用jquery做判断,发现读入jquery时,似乎好像已经被标准化了,无法从jquery对象中判断原本的img tag 的html。
html
<img id="a" src="https://placehold.it/200x200" alt="" />
<img id="b" src="https://placehold.it/200x200" alt="">
javascript
console.log($("#a"));
console.log($("#b"));
两个打印出来的元素是一模一样的。
在python中的beautifulSoup和tag中,有个接口叫做isSelfClosing正是我需要的,请问这个在javascript有类似的库和接口吗?我找了jquery和cheerio的文档都没找到
解决方案
这样可以实现,你复制到浏览器试试,可能不一定能达到你想要的效果,不过可以做到你说的那样.
document.body.innerHTML.match(/(<img.*?>)/mg).map((item)=> item.replace(/(?=.*?)\/>$/, '>'))
将原 HTML 中不合规的 img 标签全部替换
'原 HTML'.replace(/(<img.*?>)/mg, (item) => item.replace(/(?=.*?)\/>$/, '>'))
经@tengqingya提醒,修改了一下
原答案
document.body.innerHTML.match(/(<img.*?>)/mg).map((item)=> item.replace(/(?=.*?)\/?>$/, '')+'>')
这篇关于网页爬虫 - 如何用javascript解析html判断该元素最后有没有加上 / >的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文