I am trying to parse a html page with the given format:
<img class="outer" id="first" />
<div class="content" .../>
<div class="content" .../>
<div class="content" />
<img class="outer" id="second" />
<div class="content" .../>
<div class="content" .../>
<img class="outer" id="third" />
<div class="content" .../>
<div class="content" .../>
When iterating over the div tags I want to figure out whether the current div tag is under img tag with id 'first', 'second' or 'third'. Is there a way to do that? I have the list of img blocks and div blocks:
img_blocks = soup.find_all('img', attrs={'class':'outer'})
div_Blocks = soup.find_all('div', attrs={'class':'content'})
Use .find_previous_sibling
:
>>> for divtag in div_Blocks:
... print divtag.find_previous_sibling('img')
...
<img class="outer" id="first"/>
<img class="outer" id="first"/>
<img class="outer" id="first"/>
<img class="outer" id="second"/>
<img class="outer" id="second"/>
<img class="outer" id="third"/>
<img class="outer" id="third"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With