[python] #8. BeautifulSoup - find (2)


親を捜す。find_parents

  • .親はいつもスープを選ばれた親を探す機能です.
  • html = """
    <html><head><title>exoluse's velog</title></head>
    
    <body>
        <div id="div1">
            <div id="div2">
                <p class="title"><b>exoluse's velog</b></p>
            </div>
        </div>
    </body>
    
    </html>
    
    """
    
    soup = BeautifulSoup(html, "html.parser")
    
    selected1 = soup.find("p", "title").find_parents()
    
    print(selected1)
    print(type(selected1))
    
    <!-- 결과가 좀 많다. ResultSet을 좀 정리해 보겠다. -->
    [
    # 첫번째 부모
    <div id="div2">
    <p class="title"><b>exoluse's velog</b></p>
    </div>, 
    
    # 두번째 부모
    <div id="div1">
    <div id="div2">
    <p class="title"><b>exoluse's velog</b></p>
    </div>
    </div>,
    
    # 세번째 부모
    <body>
    <div id="div1">
    <div id="div2">
    <p class="title"><b>exoluse's velog</b></p>
    </div>
    </div>
    </body>, 
    
    # 네번째 부모
    <html><head><title>exoluse's velog</title></head>
    <body>
    <div id="div1">
    <div id="div2">
    <p class="title"><b>exoluse's velog</b></p>
    </div>
    </div>
    </body>
    </html>, 
    
    # 다섯번째 부모
    <html><head><title>exoluse's velog</title></head>
    <body>
    <div id="div1">
    <div id="div2">
    <p class="title"><b>exoluse's velog</b></p>
    </div>
    </div>
    </body>
    </html>
    
    ]
    <class 'bs4.element.ResultSet'>

    親を捜す。find_parent

    
    html = """
    <html><head><title>exoluse's velog</title></head>
    
    <body>
        <div id="div1">
            <div id="div2">
                <p class="title"><b>exoluse's velog</b></p>
            </div>
        </div>
    </body>
    
    </html>
    
    """
    
    soup = BeautifulSoup(html, "html.parser")
    
    selected1 = soup.find("p", "title").find_parent()
    
    print(selected1)
    print(type(selected1))
    
    <!-- .find_parent 는 바로 상위 엘리먼트를 리턴한다. -->
    <div id="div2">
    <p class="title"><b>exoluse's velog</b></p>
    </div>
    <class 'bs4.element.Tag'>

    気づいたかもしれない


    実際、これらの機能は従来の機能と変わらない.
    これ.
    これでも使えます
    .parent .parents
    .find_parent().find_parents()
    .next_sibling.next_siblings
    .find_next_sibling().find_next_siblings()
    .previous_sibling.previous_siblings
    .find_previous_sibling().find_previous_siblings()
    以前のBeautifulSoup測位を参照できます.
    https://velog.io/@exoluse/series/python-web-crawling

    次の位置に移動します。


    もう少しSelectorを掘ろうの最後の部分