Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to identify if a <p> tag is inside a <table> tag using python beautifulsoup?

How to find which p tags are inside vs outside a table tag?

<p> word outside p tag inside table tag </p>

<table>
  <tbody>
    <tr>
      <td>
        <p> word inside p tag inside table tag </p>
     </td>
   </tr>
 </tbody>
</table>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use CSS selector:

from bs4 import BeautifulSoup

html_doc = """
<p> word outside p tag inside table tag </p>

<table>
  <tbody>
    <tr>
      <td>
        <p> word inside p tag inside table tag </p>
     </td>
   </tr>
 </tbody>
</table>
"""

soup = BeautifulSoup(html_doc, "html.parser")

for p in soup.select("table p"):
    print(p.text)

Prints:

 word inside p tag inside table tag 

Or using bs4 API:

for table in soup.find_all("table"):
    for p in table.find_all("p"):
        print(p.text)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading