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

python 中,使用 beautifulSoup 获得的网页文本与在浏览器上看到的,格式不一样?

  •  
  •   vtoexsir · 2016-10-14 16:46:13 +08:00 · 3404 次点击
    这是一个创建于 2752 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如有一段 html 源码:
    html='''<span id='sp1'>span1</span>
    <span id='sp2'>span2</span>'''
    注意如上 html 源码中,sp1 与 sp2 之间有个换行,并且 sp2 之前还有几个空格.
    保存最 htm 文件,使用浏览器(ie firefox chrome)渲染后,得到的网页文本是:
    span1 span2 #注意 span1 与 span2 之间有一个空格.

    如果使用 beautifulSoup 获取网页文本,代码如下:
    from bs4 import BeautifulSoup as bs
    s=bs(html,'html5lib')
    web_text=s.get_text()
    print web_text
    结果显示如下:
    span1
    span2
    或者:print s.get_text(strip=True),则结果显示如下:
    span1span2 #注意 span1 与 span2 之间没有空格

    由此可见,使用 beautifulsoup 获取到网页文本与浏览器渲染后的网页文本,其格式是不一样的.
    那么,要想使用 beautifulsoup 获取到和浏览器渲染后的网页文本的格式一样,该怎么操作呢?
    希望方法具有普遍性,不仅仅是针对如上例子中的 htm 源码.
    多谢!
    4 条回复    2016-10-19 00:44:50 +08:00
    264768502
        1
    264768502  
       2016-10-14 21:23:19 +08:00 via iPad
    获取网页跟 bs 一点关系都没有
    网页的渲染和 python 里的 print 不是一回事
    leavic
        2
    leavic  
       2016-10-15 16:22:09 +08:00
    请把浏览器的 js 禁用
    vtoexsir
        3
    vtoexsir  
    OP
       2016-10-17 11:32:15 +08:00
    如果要获得网页源码渲染之后的网页文本,恐怕要使用类似 selenium 之类真的加载到浏览器,然后获取到.
    这样相当耗资源,速度也慢.
    我想使用 bs 来获得网页文本,而且要求格式与从网页上看到的一样.相对于使用 selenium,这样做可能快点吧.
    Arthur2e5
        4
    Arthur2e5  
       2016-10-19 00:44:50 +08:00
    https://stackoverflow.com/questions/16121001 ,直接插空格。
    当然想模仿一下 br 处理的话还得再费点事。 strip 那玩意本来就是拿来吃空格的,别指望它……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2898 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:05 · PVG 08:05 · LAX 17:05 · JFK 20:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.