zoukankan      html  css  js  c++  java
  • python——beautifulsoup标签搜索以及信息提取

    原文:https://www.cnblogs.com/my1e3/p/6657926.html

     

    一、 查找a标签


    (1)查找所有a标签

    复制代码
    >>> for x in soup.find_all('a'):
        print(x)
        
    <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
    <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
    <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
    复制代码


    (2)查找所有a标签,且属性值href中需要包含关键字“lacie

    >>> for x in soup.find_all('a',href = re.compile('lacie')):
        print(x)
    
    <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>


    (3)查找所有a标签,且字符串内容包含关键字“Elsie”

    >>> for x in soup.find_all('a',string = re.compile('Elsie')):
        print(x)
        
    <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>


    (4)查找body标签的所有子标签,并循环打印输出

    复制代码
    >>> for x in soup.find('body').children:
        if isinstance(x,bs4.element.Tag):        #使用isinstance过滤掉空行内容
            print(x)
            
    <p class="title"><b>The Dormouse's story</b></p>
    <p class="story">Once upon a time there were three little sisters; and their names were
    <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
    <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
    <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
    and they lived at the bottom of a well.</p>
    复制代码


    二、信息提取(链接提取)


    (1)解析信息标签结构,查找所有a标签,并提取每个a标签中href属性的值(即链接),然后存在空列表;

    复制代码
    >>> linklist = []
    >>> for x in soup.find_all('a'):
        link = x.get('href')
        if link:
            linklist.append(link)
           
    >>> for x in linklist:        #验证:环打印出linklist列表中的链接
        print(x)
      
    http://example.com/elsie
    http://example.com/lacie
    http://example.com/tillie
    复制代码


    小结:链接提取 <---> 属性内容提取 <---> x.get('href')

    (2)解析信息标签结构,查找所有a标签,且每个a标签中href中包含关键字“elsie”,然后存入空列表中;

    复制代码
    >>> linklst = []
    >>> for x in soup.find_all('a', href = re.compile('elsie')):
        link = x.get('href')
        if link:
            linklst.append(link)
        
    >>> for x in linklst:        #验证:循环打印出linklist列表中的链接
        print(x)
        
    http://example.com/elsie
    复制代码

    小结:在进行a标签查找时,加入了对属性值href内容的正则匹配内容 <---> href = re.compile('elsie')

    (3)解析信息标签结构,查询所有a标签,然后输出所有标签中的“字符串”内容;

    复制代码
    >>> for x in soup.find_all('a'):
        string = x.get_text()
        print(string)
       
    Elsie
    Lacie
    Tillie
    复制代码

     

    本博客为记录本人遇到问题时所找到的解决方案,且均经过本人亲测可用,如有侵权请联系添加来源或删除文章,谢谢。
  • 相关阅读:
    python2与3自由切换
    ubuntu 安汉google浏览器
    ros 下常用的依赖库
    imu tool使用
    g2o 初始化
    linux 解压缩
    sudo apt-get update 没有公钥,无法验证下列签名
    ceres g2o 安装
    ubuntu 下开源安装
    Nhibernate中 Many-To-One 中lazy="proxy" 延迟不起作用的原因
  • 原文地址:https://www.cnblogs.com/heymonkey/p/11775556.html
Copyright © 2011-2022 走看看