V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
vtoexsir
V2EX  ›  Python

BeautifulSoup 怎么直接插入一段 html 代码?

  •  
  •   vtoexsir · 2016-10-21 15:35:55 +08:00 · 2493 次点击
    这是一个创建于 2744 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import bs4 import BeautifulSoup as bs
    h="<b>b-text</b>"
    s=bs(h,'html5lib')
    b_s=s.b.string
    html_code="<a>a-string</a>"
    b_s.replace_with(html_code) 
    print b
    ## <b>&lt;a&gt;a-string&lt;/a&gt;</b>
    

    如上代码可以顺利执行,只是,html_code 里边的尖括号都被 bs 转了. 那怎么样才能让 bs 不要转义我插入的字符串呢? 多谢您的回复!

    5 条回复    2016-10-24 12:04:29 +08:00
    wyntergreg
        1
    wyntergreg  
       2016-10-21 15:52:00 +08:00
    vtoexsir
        2
    vtoexsir  
    OP
       2016-10-22 09:33:08 +08:00
    @wyntergreg 多谢您的回复,我知道 bs.replace_with(tag_or_navstr_or_str)的参数是 bs 的 tag 类型或者 navigableString 类型或者干脆是 python 的字符串类型.
    我就是想怎么插入一段 html 代码,让 bs 自动正确识别,代码该怎么写?
    XYxe
        3
    XYxe  
       2016-10-22 09:47:02 +08:00
    from bs4 import BeautifulSoup
    h="<b>b-text</b>"
    s= BeautifulSoup(h)
    s.b.string.replace_with("")
    new_tag = s.new_tag("a")
    new_tag.string = "a-string"
    s.b.string.insert_before(new_tag)
    print s.b
    # <b><a>a-string</a></b>
    不知道这样符不符合你的要求
    vtoexsir
        4
    vtoexsir  
    OP
       2016-10-24 12:03:47 +08:00
    @XYxe 多谢您的回复!
    您的方法是常用的路子,可以达到要求.但是这样做逻辑上不太直接.
    我的代码(伪代码)一看,就知道是用一段 html 源码替换 b 标签的文本内容.
    vtoexsir
        5
    vtoexsir  
    OP
       2016-10-24 12:04:29 +08:00
    看来我是强人所难了!
    谢谢各位!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1915 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 16:24 · PVG 00:24 · LAX 09:24 · JFK 12:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.