V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
antxiaoye
V2EX  ›  Go 编程语言

求教使用 Golang 替换 html 的标签里的内容

  •  
  •   antxiaoye · 2022-10-19 16:37:41 +08:00 · 1661 次点击
    这是一个创建于 555 天前的主题,其中的信息可能已经有所发展或是发生改变。

    直接上想要达到的效果吧;

    替换前内容:

    <h1>h1.1</h1><h1>h1.2</h1><div>div1<span>span1</span></div>
    

    希望替换后内容:

    <h1>Replace_h1.1</h1><h1>Replace_h1.2</h1><div>Replace_div1<span>Replace_span1</span></div>
    

    目前楼主使用了PuerkitoBio/goquery可以实现基本功能,但是缺点是会自行补充html标签,例如:

    // 使用 goquery 替换的效果 fmt.Println(doc.Html())
    <html><head></head><body><h1>Replace_h1.1</h1><h1>Replace_h1.2</h1><div>Replace_div1<span>Replace_span1</span></div></body></html>
    
    

    <html><head></head><body>这些标签是楼主并不想要的?

    求大佬们解惑。

    有什么办法可以避免这种标签补全呢?或者有其他方案或者其他包可以实现。

    13 条回复    2022-10-21 16:37:02 +08:00
    dreasky
        1
    dreasky  
       2022-10-19 17:01:26 +08:00
    正则表达式不简单吗
    dog82
        2
    dog82  
       2022-10-19 17:01:52 +08:00
    感觉正则可以实现,跟 go 没关系
    duan602728596
        3
    duan602728596  
       2022-10-19 17:11:10 +08:00   ❤️ 1
    我的建议是使用 goquery 替换后,再使用正则把<html><head></head><body>和</body></html>这段去掉
    antxiaoye
        4
    antxiaoye  
    OP
       2022-10-19 18:32:28 +08:00
    如果没有一个包可以用的话,我会选择用正则的,但是还是想以最快的方法实现这个功能。
    securityCoding
        5
    securityCoding  
       2022-10-19 20:08:54 +08:00 via Android
    楼上的 goquery
    luvroot
        6
    luvroot  
       2022-10-19 20:16:31 +08:00
    "github.com/antchfx/htmlquery"

    获取到的 doc 对象进行操作,不像要的可以把 node 找到后删除。

    h1 找到后 是个 list 。然后循环的进行替换

    for index,nodeH1 :=range. xxx {
    if nodeH1!=nil {
    origin :=htmlquery.htmlquery.InnerText
    //根据某种要求进行替换。然后回写
    }
    }
    ysc3839
        7
    ysc3839  
       2022-10-20 06:48:34 +08:00 via Android
    不能先取到 body 再 get html 吗?
    antxiaoye
        8
    antxiaoye  
    OP
       2022-10-20 16:31:47 +08:00
    @ysc3839 需要替换的字符串没有 body 哦。
    ysc3839
        9
    ysc3839  
       2022-10-20 16:32:45 +08:00
    @antxiaoye 从结果来看是那个库自己加上了 body 吧?
    Joker123456789
        10
    Joker123456789  
       2022-10-20 17:32:20 +08:00
    这不就是个 xml 吗?
    antxiaoye
        11
    antxiaoye  
    OP
       2022-10-21 10:07:25 +08:00
    我直接用正则吧,貌似没有合适的库。
    antxiaoye
        12
    antxiaoye  
    OP
       2022-10-21 10:08:44 +08:00
    @ysc3839 是的,这个库自己补全这些标签,所以不太符合我希望达到的效果,我还是用正则吧~
    youngster
        13
    youngster  
       2022-10-21 16:37:02 +08:00
    go template 试试?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   947 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 20:33 · PVG 04:33 · LAX 13:33 · JFK 16:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.