BeautifulSoup4的基本使用

BeautifulSoup4的基本使用

序:BeautifulSoup是python解析html非常好用的第三方库!

安装:

    pip install beautifulsoup4

基本使用:

    from bs4 import BeautifulSoup

    html_str = """
        <ul>
            <li>
                <a href="http://www.baidu.com/">百度一下</a>
            </li>
            <li>合适的话发多少</li>
            <li>
                <a class="baidu" href="http://www.baidu.com/">不会发生看到</a>
            </li>
            <li>
                <a  id="lagou" href="http://www.lagou.com/">lagou</a>
            </li>
            <li>
                <label class="enterText enterArea">列表图预览:</label>
                <p class="enterImg">
                    <img id="previewImage" title='mmm' src="http://www.google.com/logo.png"/>
                </p>
                <div class="Validform_checktip">范德萨范德萨</div>
            </li>
        </ul>
    """

    soup = BeautifulSoup(html_str,'html.parser')

    #html对象  text文本去掉标签
    # print(soup)
    # print(soup.text)


    # <class 'bs4.BeautifulSoup'> 对象类型
    # print(type(soup))

    # 查找a标签 .text打印a的内容
    # print(soup.find('a'))
    # print(soup.find('a').text)

    # 查找a标签 class=baidu的
    # print(soup.find('a',class_='baidu'))

    # 查找id=lagou
    # print(soup.find(id='lagou'))

    # 查找title='mmm' 前边可以写具体找哪个标签
    # print(soup.find(title='mmm'))

    # find_all 找所有  返回一个list 数组类型
    # print(soup.find_all('a'))
    # print(soup.find_all('a')[0]) #第一个
    all_a = soup.find_all('a')
    for item in all_a:
        if item:
            # print(item.attrs)
            print(item.attrs['href']) #dict类型

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 环境管理管理Python版本和环境的工具。p–非常简单的交互式python版本管理工具。pyenv–简单的Pyth...
    MrHamster阅读 9,240评论 1 61
  • Python 资源大全中文版 awesome-python[https://github.com/vinta/aw...
    万色星辰阅读 13,264评论 0 255
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,716评论 6 427
  • 看电影于我而言,只是看热闹。我不懂什么构图分镜,也不了解库布里克北野武,所以吸引我的电影往往都是讲了一个好故事,而...
    贰仟阅读 1,605评论 0 0
  • 吧台的角落,抿着淡绿色的不知名的酒歪着身子斜坐的你就那么带着奇怪的微笑瞧着我,有趣的很。我想这就是我们后来的甜蜜,...
    惟夢天騎阅读 1,202评论 0 0