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())

  • 相关阅读:
    leetcode 92. 反转链表 II
    leetcode记录1 快速排序
    Jmeter入门总结
    Jmeter 元件作用域、集合点、检查点
    Jmeter 实例
    badboy脚本开发
    Jmeter 常用功能介绍
    简单的自创线程池
    多线程
    IO多路复用
  • 原文地址:https://www.cnblogs.com/sfzyk/p/6516683.html
Copyright © 2011-2022 走看看