beautifulsoup

How to find the previous sibling <h1>-<h6> in BeautifulSoup?


To find the previous sibling of the div element/variable, which is a <h1> - this works:

heading = div.find_previous_sibling('h1')

However; to find the previous sibling, which could be any of <h1>, <h2>, <h3>, <h4>, <h5> or <h6> - I tried to use a CSS-style selector, but this does not work:

heading = div.find_previous_sibling('h1, h2, h3, h4, h5, h6')

How can we find the previous sibling, which is any heading?


Solution

  • According to the documentation, the first argument of the find_previous_sibling function can be a list.

    Have you tried this ?

    heading = div.find_previous_sibling(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])