zoukankan      html  css  js  c++  java
  • PYTHON网络爬虫与信息提取[BeautifulSoup](单元四)

    1 简介

    from bs4 import BeautifulSoup

    soup=BeautifulSoup(<p>data</p>,'html.parser')

    2 基本元素

    解析,遍历,维护,标签树的库

    <p class="title"> ...</p>    tag对

    名称 (属性 attributes)

    beautifulsoup 或bs4

    from bs4 import BeautifulSoup

    import bs4

    beautifulSoup 雷

    html--------标签树(字符串)转换为beautifulsoup类

    from bs4 import BeautifulSoup 

    soup=

    注:解析器(4种)

    html.parser    安装bs4库

    lxml      pip install lxml

    xml                同上

    html5lib    pipinstall html5lib

    beautiful 类的基本元素

    Tag  标签 尖括号开头结尾

    Name  格式:<tag>.name  <p>的名字是 ''p''

    Attributes      标签的属性,字典形式组织  <tag>.attrs

    NavigableString 标签内非属性字符串  表示尖括号之间的内容

    soup.a.string 就可以了

    Comment     标签内字符串的注释部分

    用string 也可以得出这个类型

    3 标签树的遍历 

    .contents 获得子节点的列表

    .children 获得子节点的迭代形式

    .descendants 获得子孙的迭代形式

    儿子节点不管包括标签 还包括

    soup.body.contents

    .parent 节点的父亲标签

    .parnets 节点的先辈形式迭代版的

    平行遍历(返回按照html文本顺序的节点标签)

    平行遍历时实在同一个父标签下的遍历

    .next_sibling

    .previous_sibling

    .next_siblings   迭代版

    .next_previous_siblings 迭代版

    4 基于bs4显示html的内容

    from bs4 import BeautifulSoup

    soup=BeautifulSoup(demo,"html.parser")   //加载解析器的语句

    soup.prettify()  //soup 是 BeautifulSoup类型 用以解析html 或者遍历html

    "prettify()方法非常好用"

    #增加换行符

    print(soup.prettify())

  • 相关阅读:
    Could not continue scan with NOLOCK due to data movement
    Paxos共识算法详解
    从CAP到Paxos算法
    一文读懂拜占庭将军问题
    Paxos 与拜占庭将军问题
    CAP、BASEd、二阶段提交协议、三阶段提交协议、拜占庭将军问题、paxos、Raft、ZAB、NWR
    拜占庭将军
    三分钟教您看懂中本聪是如何解决拜占庭将军问题的
    SimpleDateFormat线程不安全原因及解决方案
    mysql having多个条件
  • 原文地址:https://www.cnblogs.com/sfzyk/p/6516683.html
Copyright © 2011-2022 走看看