zoukankan      html  css  js  c++  java
  • BeautifulSoup的用法

    BeautifulSoup是一个模块,该模块用于接收一个HTML或XML字符串,然后将其进行格式化,之后遍可以使用他提供的方法进行快速查找指定元素,从而使得在HTML或XML中查找指定元素变得简单。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    from bs4 import BeautifulSoup
     
    html_doc = """
    <html><head><title>The Dormouse's story</title></head>
    <body>
    asdf
        <div class="title">
            <b>The Dormouse's story总共</b>
            <h1>f</h1>
        </div>
    <div class="story">Once upon a time there were three little sisters; and their names were
        <a  class="sister0" id="link1">Els<span>f</span>ie</a>,
        <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
        <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
    and they lived at the bottom of a well.</div>
    ad<br/>sf
    <p class="story">...</p>
    </body>
    </html>
    """
     
    soup = BeautifulSoup(html_doc, features="lxml")
    # 找到第一个a标签
    tag1 = soup.find(name='a')
    # 找到所有的a标签
    tag2 = soup.find_all(name='a')
    # 找到id=link2的标签
    tag3 = soup.select('#link2')

    再给大家举个经常用的例子:

    一,这个参数需要一个字符串,response是一个对象,response.text是字符串,

    二,’lxml‘是解析器,指定用lxmL做解析器

    三,四,这两个合在一起,是找到类选择器为btnlinks的p标签

    五,找出标签元素里href对应的url

    注意:find得到的是第一个标签元素,find_all是得到的是一个列表,元素是所有的符合条件的标签,可以通过下标获取元素。

  • 相关阅读:
    hdu 6049 Sdjpx Is Happy
    L2-012. 关于堆的判断
    L2-010. 排座位
    L2-009. 抢红包
    L2-007. 家庭房产
    L2-008. 最长对称子串
    L2-011. 玩转二叉树
    l2-006 树的遍历
    l2-005
    l1-20 帅到没朋友
  • 原文地址:https://www.cnblogs.com/chaojiyingxiong/p/9749687.html
Copyright © 2011-2022 走看看