zoukankan      html  css  js  c++  java
  • Python_爬虫_BeautifulSoup网页解析库

    BeautifulSoup网页解析库

    from bs4 import BeautifulSoup

    0.BeautifulSoup网页解析库包含 的 几个解析器

    • Python标准库【主要,系统自带;】

      使用方法: BeautifulSoup(markup,"html.parser")【注:markup是html文档】
      Python的内置标准库

      案例:

    
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup.(html,'html.parser')
    
    print(soup.title.string)
    
    
    • lxmlHTML解析器

      BeautifulSoup(markup,'lxml)
      速度快、需要安装C语言库

    • lxml XML解析器

      使用方法:BeautifulSoup(markup,"xml")
      速度快,唯一支持XML的解析器、需要安装C语言库

    • html5lib

      BeautifulSoup(markup,"html5lib")
      容错性好,以浏览器的形式解析文档,生成html5格式的文档,但是速度慢

    1.BeautifulSoup基本使用

    
    
    #!/usr/bin/env python 
    # -*- coding:utf-8 -*- 
    
    html="""
        <html>
            <head>
                <title>The Domouse's story</title>
            </head>
            <body>
                <p class="title" name="Domouse"><b>The Domouse's story</b></p>
                <p class="story">Once upon a time there were three little sisters;and their names were</p>
                <a href="http://www.baidu.com">百度</a>
                <p class="story">...</p>
            </body>
        </html>
        """
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html,'lxml')
    #获取标签正文内容
    print("标签内正文内容:" + soup.title.name)
    #获取属性内容
    print("属性内容" + soup.p.attrs['name'])
    #获取内容
    print("获取内容" + soup.p.string)
    #获取嵌套内容(多个筛选条件)
    print("获取嵌套内容" + soup.head.title.string)
    #子节点 和 孙节点【重要,,当目标标签没有id 或 class时候必须用这个】
    print("子节点" + soup.p.contents)   #全部子节点,返回的是列表形式
    print("子节点" + soup.p.contents[2])   #第三个一级子节点,不管是什么标签
    #1. 子节点#子节点【迭代器,只能用循环形式拿到数据】
    soup = BeautifulSoup(html,"lxml")
    print(soup.p.children)
    for i,child in enumerate(soup.p.children):
        print(i,child)
    #2.子孙节点
    soup = BeautifulSoup(html,"lxml")
    print(soup.p.descendants)
    for i,child in enumerate(soup.p.descendants):
        print(i,child)
    #父节点 和 祖先借点
    print(list(enumerate("父节点:" + soup.a.parent))) #父节点
    print(list(enumerate("祖父节点:" + soup.a.parent))) #祖父点
    #获取兄弟节点
    
    print("后面的兄弟节点" + list(enumerate(soup.a.next_siblings)))    #后面的兄弟节点
    print("前面的兄弟节点" + list(enumerate(soup.a.previous_slblings)))    #前面的兄弟节点
    
    
  • 相关阅读:
    go包之logrus显示日志文件与行号
    linux几种快速清空文件内容的方法
    (转)CSS3之pointer-events(屏蔽鼠标事件)属性说明
    Linux下source命令详解
    控制台操作mysql常用命令
    解决beego中同时开启http和https时,https端口占用问题
    有关亚马逊云的使用链接收集
    favicon.ico--网站标题小图片二三事
    js获取url协议、url, 端口号等信息路由信息
    (转) Golang的单引号、双引号与反引号
  • 原文地址:https://www.cnblogs.com/hellangels333/p/8595477.html
Copyright © 2011-2022 走看看