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
holajamc
V2EX  ›  Python

求问网页标签获取

  •  
  •   holajamc · 2017-08-17 16:46:46 +08:00 · 1218 次点击
    这是一个创建于 2444 天前的主题,其中的信息可能已经有所发展或是发生改变。

    使用 bs4 可以很轻松获得网页文字内容,但是如果想获得网页的标签信息应该怎么做?

    假如网页源码是

    <html>
    
    <head>
        <title>The Dormouse's story</title>
    </head>
    
    <body>
        <p class="title"><b>The Dormouse's story</b></p>
    
        <p class="story">Once upon a time there were three little sisters; and their names were
            <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
            <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
            <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p>
    
        <p class="story">...</p>
    </body>
    
    </html>
    

    获得网页标签结构

    <html>
    
    <head>
        <title> </title>
    </head>
    
    <body>
        <p class="title"><b> </b></p>
    
        <p class="story">
            <a href="http://example.com/elsie" class="sister" id="link1"> </a>
            <a href="http://example.com/lacie" class="sister" id="link2"> </a>
            <a href="http://example.com/tillie" class="sister" id="link3"> </a> </p>
    
        <p class="story"> </p>
    </body>
    
    </html>
    
    1 条回复    2017-08-18 10:37:58 +08:00
    Droi
        1
    Droi  
       2017-08-18 10:37:58 +08:00
    你是不是想要这些内容。
    我是熬两次汤,熬出来的。不知道其他人有没有其他好用的方法。
    官方教程的快速开始有这个 get()方法

    from bs4 import BeautifulSoup
    >>> html = """<html> ..... </html>"""
    >>> soup = BeautifulSoup(html, "html.parser")
    >>> ssoup = BeautifulSoup(str(soup.find_all(attrs={'class':'story'})), "html.parser")
    >>> ssoup.find_all('a')[0].get('href')
    'http://example.com/elsie'
    >>>
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3662 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:28 · PVG 18:28 · LAX 03:28 · JFK 06:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.