推荐学习书目
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 · Oct 21, 2016 · 3069 views
    This topic created in 3574 days ago, the information mentioned may be changed or developed.
    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 replies    2016-10-24 12:04:29 +08:00
    vtoexsir
        2
    vtoexsir  
    OP
       Oct 22, 2016
    @wyntergreg 多谢您的回复,我知道 bs.replace_with(tag_or_navstr_or_str)的参数是 bs 的 tag 类型或者 navigableString 类型或者干脆是 python 的字符串类型.
    我就是想怎么插入一段 html 代码,让 bs 自动正确识别,代码该怎么写?
    XYxe
        3
    XYxe  
       Oct 22, 2016
    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
       Oct 24, 2016
    @XYxe 多谢您的回复!
    您的方法是常用的路子,可以达到要求.但是这样做逻辑上不太直接.
    我的代码(伪代码)一看,就知道是用一段 html 源码替换 b 标签的文本内容.
    vtoexsir
        5
    vtoexsir  
    OP
       Oct 24, 2016
    看来我是强人所难了!
    谢谢各位!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3614 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 04:43 · PVG 12:43 · LAX 21:43 · JFK 00:43
    ♥ Do have faith in what you're doing.