如何使用 jsoup 替换标签

发布于 2024-12-28 20:28:38 字数 344 浏览 4 评论 0原文

我想用 div 标签替换所有图像标签。我可以选择所有标签,并且我知道我必须使用 replaceWith。但我无法使用它。

如果我使用 TextNode 将其替换为

;
并转换为 <div>我的 div </div>

我知道 &lt;&gt; 是用于<>

请帮助我。

I want to replace all image tags with div tag. I am able to select all tags and I know that I have to use replaceWith. But I am unable to use it.

And if I use TextNode for replacing it with <div> </div> and it converts into &lt;div&gt; my div &lt;/div&gt;

I know &lt; and &gt; is for < and >

Please help me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千柳 2025-01-04 20:28:38

我猜您正在替换为 element.replaceWith(new TextNode("

"),"");

Textnode 用于文本和转义内容 - 这就是您看到 HTML 实体的原因。您需要替换为标签,因此请执行诸如 element.replaceWith(new Element(Tag.valueOf("div"), "")); 之类的操作。

I guess you are replacing with element.replaceWith(new TextNode("<div></div>"),"");?

A Textnode is for text and escapes content - thats why you see the HTML entities. You need to replace with a tag, so do something like element.replaceWith(new Element(Tag.valueOf("div"), ""));.

oО清风挽发oО 2025-01-04 20:28:38

这是实现这一目标的最简单方法:

 Elements elements= doc.getElementsByTag("img");
 elements.tagName("div");

希望这对您有用。

This is the simplest way of achieving this:

 Elements elements= doc.getElementsByTag("img");
 elements.tagName("div");

Hope that is working for you.

只需使用 find 方法并传递特定标签
let tag = soup.find('tag_name') tag.name = 'new_tag';//替换标签

对于多个标签,只需放入循环内
let tag = soup.findAll('tag_name'); if (tag) { for (let i = 0; i < tag.length; i++) { tag[i].name = 'your_new_tag'; } } }

just use find method and pass specific tags
let tag = soup.find('tag_name') tag.name = 'new_tag';//replaced tag

for multiple tag just put inside loop
let tag = soup.findAll('tag_name'); if (tag) { for (let i = 0; i < tag.length; i++) { tag[i].name = 'your_new_tag'; } }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文