zoukankan      html  css  js  c++  java
  • Python网络爬虫与信息提取(二)(BeautifulSoup库)

    BeautifulSoup库是解析、遍历、维护.html或.xml的功能库

    ①BeautifulSoup库的安装:

    在cmd命令行中输入: pip install beautifulsoup4即可

    ②BeautifulSoup库的引用:

    from bs4 import BeautifulSoup

    BeautifulSoup库,也叫beautifulsoup4或bs4

    ③检测Beautiful Soup库是否安装成功以及使用BeautifulSoup库对网页进行解析:

    image

    整个解析过程的主要代码:

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

    ④BeautifulSoup库的四种解析器:

    image

    ⑤BeautifulSoup类的基本元素及相应用法:

    image

    在DOS命令下:

    C:UsersAdministratorpython

    image

    >>>import requests

    >>>r=requests.get(“http://python123.io/ws/demo.html”)

    >>>r.text

    image

    >>>demo=r.text

    >>>from bs4 import BeautifulSoup

    >>>soup=BeautifulSoup(demo,”html.parser”)

    >>>print(soup.prettify())

    image

    >>>soup.title

    image

    >>>tag=soup.a

    >>>tag

    image

    image

    Comment的用法:

    image

    ⑥基于bs4库的HTML内容遍历方法

    image

    标签树的下行遍历:

    image

    遍历儿子节点 ==>  for child in soup.body.children:

           print(child)

    遍历子孙节点 ==>  for child in soup.body.children:

            print(child)

    image

    标签树的上行遍历:

    属性  .parent      说明    节点的父类标签

    属性  .parents    说明     节点先辈标签的迭代类型,用于循环遍历先辈节点

    标签树的平行遍历:

    image

    平行遍历发生在同一个父节点下的各节点间

    1)遍历后续节点

    for sibling in soup.a.next_siblings:

          print(sibling)

    2)遍历前续节点

    for sibling in soup.a.previous_siblings:

          print(sibling)

    天晴了,起飞吧
  • 相关阅读:
    利用集群因子优化
    HighCharts之2D对数饼图
    HighCharts之2D回归直线的散点
    HighCharts之2D柱状图、折线图的组合多轴图
    Oracle Data Guard_ 主库添加或删除在线重做日志文件
    Oracle Data Guard_ 主库重命名数据文件
    Oracle Data Guard_ 主备库传输表空间
    打开页面报错
    HighCharts之2D柱状图、折线图的组合双轴图
    HighCharts之2D柱状图、折线图和饼图的组合图
  • 原文地址:https://www.cnblogs.com/jianqiao123/p/11176124.html
Copyright © 2011-2022 走看看