• python库学习笔记——BeautifulSoup处理子标签、后代标签、兄弟标签和父标签


    首先,我们来看一个简单的网页https://www.pythonscraping.com/pages/page3.html,打开后:

    右键“检查”(谷歌浏览器)查看元素:


    用导航树的形式简单表示出来:


    可知:

    tr是table的子标签

    tr、th、td、img、span标签都是table的后代标签


    一般情况下,bbs0bj.body.h1选择的是body标签后代里的第一个h1标签,不会去找body外面的标签

    类似的,bs0bj.div.findall("img")会找到第一个div标签,然后获取这个div后代里面所有的img标签

    1. 处理子标签和后代标签

    如果你想获得子标签,可以用.children标签:

    from urllib.request import urlopen
    from bs4 import BeautifulSoup
    
    html = urlopen("http://www.pythonscraping.com/pages/page3.html")
    bsObj = BeautifulSoup(html)
    
    for child in bsObj.find("table",{"id":"giftList"}).children:
        print(child)

    部分结果如下:


    如果你用descendants()函数,就会获得每个后代标签


    2. 处理兄弟标签

    BeautifulSoup中的next_siblings()很擅长处理带标题行的表格:
    from urllib.request import urlopen
    from bs4 import BeautifulSoup
    html = urlopen("http://www.pythonscraping.com/pages/page3.html")
    bsObj = BeautifulSoup(html, "html.parser")
    
    for sibling in bsObj.find("table",{"id":"giftList"}).tr.next_siblings:
        print(sibling) 
    得到部分结果如下:


    如果你很擅长找到一组兄弟标签中的最后一个标签,那么previous_siblings()函数
    另外,next_sibling(),previous_siblings()返回单个标签

    3. 处理父亲标签

    抓取网页的时候,父标签用到的很少,用parent和parents抓取,举个例子:
    from urllib.request import urlopen
    from bs4 import BeautifulSoup
    
    html = urlopen("http://www.pythonscraping.com/pages/page3.html")
    bsObj = BeautifulSoup(html, "html.parser")
    print(bsObj.find("img",{"src":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text())
    
    输出:
    $15.00
    
    
    可以这样理解:
    
    
    
    (1)选择图片标签
    (2)选择图片标签的父标签<td>
    (3)选择标签<td>前面的一个兄弟标签
    (4)选择标签中的文字

    参考资料:《python网络数据采集》

    $15.00
  • 相关阅读:
    在数据库中 存储图片 以及 在界面中显示图片(存储图片路径)- 这种方法相对与存储二进制文件好
    # 会员注册与登录模块
    文本文件从磁盘读取、写入
    简单的web三层架构系统【第五版】
    Nginx负载均衡中后端节点服务器健康检查的一种简单方式
    编译安装php-7.1.17及部分扩展
    wkhtmltopdf 安装过程不包含php扩展部分
    Centos6下安装中文字体
    xen 配置vm 跟随xen server一起启动
    CENTOS 升级Nodejs 到最新版本
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9411638.html
Copyright © 2020-2023  润新知