Python beautifulsoup4解析 数据提取 基本使用

Python beautifulsoup4解析 数据提取 使用介绍&常用示例


文章目录

  • Python beautifulsoup4解析 数据提取 使用介绍&常用示例
  • 前言
  • 二、from bs4 import BeautifulSoup
  • 1.pip install beautifulsoup4
  • 2.Beautiful用法介绍
  • 2.1 解析html源码创建创建Beautifulsoup对象
  • 2.2 beautiful对象的常用属性和方法
  • 2.3 find、find_all、CSS选择器 根据条件提取元素
  • 3.常用代码
  • 4.对象类型介绍
  • 总结

  • 前言

    Beautiful Soup是Python的一个网页解析库,处理快捷; 支持多种解析器,功能强大。教程细致讲解Beautiful Soup的深入使用、节点选择器、CSS选择器、Beautiful Soup4的方法选择器等重要知识点,是学好爬虫的基础课程。


    提示:以下是本篇文章正文内容,下面案例可供参考
    建议把代码复制到编译工具中运行跑几次,认真看一下输出结果方便更好的理解, beautifulsoup4=4.11.1

    二、from bs4 import BeautifulSoup

    1.pip install beautifulsoup4

    pip install beautifulsoup4 -i https://pypi.tuna.tsinghua.edu.cn/simple

    2.Beautiful用法介绍

    2.1 解析html源码创建创建Beautifulsoup对象

    from bs4 import BeautifulSoup
    web_html = """
    <html>
    <head>
        <title id="title">The Dormouse's story1</title>
    </head>
    <body>
        <p class="story">
            <a href="http://example.com/elsie1" class="link11" id="link1">EXI-XZ</a>,
            <a href="http://example.com/elsie2" class="link11" id="link2">Elsie</a>,
            <a href="http://example.com/lacie" class="link22" id="link3">Lacie</a> and
            <a href="http://example.com/tillie" class="link33" id="link4">Tillie</a>;
        </p>
        <ul class="ul_test", id="abc">
            <li class="li_test" href="http://example.com/li">AA</li>
            <li class="li_test" href="http://example.com/li">BB</li>
            <li class="li_test" href="http://example.com/li">CC</li>
        </ul>
        <div class="div_test">
            <p>div模块-p标签</p>
        </div>
    </body>
    </html>
    """
    soup = BeautifulSoup(web_html, 'lxml')  # 解析网页源码创建Beautifulsoup对象 
    

    2.2 beautiful对象的常用属性和方法

    web_html = soup.prettify()  # 返回格式化后的源码,str类型
    title_tag = soup.title  # 返回源码中第一个title标签(源码),element.Tag类型
    print('title_tag:', title_tag, type(title_tag))
    title_content = soup.title.string  # 提取title标签的文本, element.NavigableString,下面有多个标签内容则返回None
    print('title_content:', title_content, type(title_content))
    all_p_content = soup.body.get_text()  # 提取body下面的所有p标签,str类型
    print('all_p_content:', all_p_content, type(all_p_content))
    a_href = soup.a['href']  # 提取第一个a标签的href属性,str类型
    print("a_href:", a_href, type(a_href))
    

    2.3 find、find_all、CSS选择器 根据条件提取元素

    # find -- 返回符合查询条件的第一个标签
    # 组合条件一
    find_group_result = soup.find(name='a', string='EXI-XZ')  # name(标签名),string(标签的文本),element.Tag类型
    print('find_group_result:', find_group_result, type(find_group_result))
    # 组合条件二,推荐第二种方式,字典方式key,value
    find_attrs_result = soup.find(attrs={'class': 'link11', 'id': 'link1'})  # 指定属性,element.Tag类型,
    print('find_attrs_result:', find_attrs_result, type(find_attrs_result))
    find_attrs_result.get('href')  # 获取该对象的属性href
    find_attrs_result.text  # 获取该对象标签的文本,不同于find_attrs_result.string,下面有多个标签会全部返回而不是None
    find_ul_result = soup.find(attrs={'class': "ul_test", 'id': 'abc'})
    print('ul_tag_result:', find_ul_result.text, type(find_ul_result))  # element.Tag
    
    # find_all -- 返回符合查询条件的所有标签, list类型
    find_li_list = soup.find_all(name='li', attrs={'class': "li_test"}, limit=2)  # limit(返回前两个标签)
    find_li_list[0].attrs  # 提取标签的所有属性
    
    # CSS选择器 -- list类型
    div_tag = soup.select('div,.div_test')  # 取class为"div_test"的div标签,list类型,  #=id   .=class
    print('div_tag:', div_tag, type(div_tag))
    div_tag = soup.select('div[class="div_test"]')  # 等同于soup.select('div,.div_test')
    print('div_tag:', div_tag, type(div_tag))
    print("div下p标签的文本:", div_tag[0].select("p")[0].text)  # 取div中的第一个p标签的文本
    

    3.常用代码

    import requests
    from bs4 import BeautifulSoup
    url = "xxxxxxxxxxxxxxxxx"
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'}
    response = requests.get(url=url, headers=headers)
    web_html = response.text
    soup = BeautifulSoup(web_html, 'lxml')  # 解析网页源码创建Beautifulsoup对象
    

    4.对象类型介绍

    BeautifulSoup4四大对象种类
    bs4.element.Tag 通俗点讲就是HTML中的一个个标签,有很多属性和方法可以更加详细的提取内容
    NavigableString 得到了标签源码,通过对象的属性和方法可以提取标签内部文字(.string)和属性(xx['class'])
    BeautifulSoup 表示一个文档的全部内容.
    Comment 一个特殊类型的NavigableString对象,其输出的内容不包括注释符号。
    

    总结

    小洲提示:建议把代码复制到编译工具中运行跑几次,认真看一下输出结果方便更好的理解, beautifulsoup4=4.11.1

    以上就是今天要讲的内容,本文仅仅简单介绍了beautifulsoup4解析web源码的使用,而beautifulsoup4提供了大量能使我们快速便捷地处理数据的函数和方法,后续有关于beautifulsoup4的常用代码会在这篇博客中持续更新。
    Beautifulsoup4官方文档:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python beautifulsoup4解析 数据提取 基本使用

    发表回复