sledgefox
sledgefox

Reputation: 19

python beautifulsoup search across multiple lines

I am trying to search for the P/E ratio of a finance page, from the input code shown below. So, essentially I am trying to extract '48.98' from the source. As the structure is same for Market cap, book value, etc. I am unable to frame the correct code for a soup.find

Would be very grateful for the correct structure of the soup.find code. I am a newbie and sorry if i am asking something very basic.. Thanks in advance !

<div class="FL" style="width:210px; padding-right:10px">
<div class="PA7 brdb">
<div class="FL gL_10 UC">MARKET CAP (Rs Cr)</div>
<div class="FR gD_12">41,364.28</div>
<div class="CL"></div>
</div>
<div class="PA7 brdb">
<div class="FL gL_10 UC">P/E</div>
<div class="FR gD_12">**48.98**</div>
<div class="CL"></div>
</div>
<div class="PA7 brdb">
<div class="FL gL_10 UC">BOOK VALUE (Rs)</div>
<div class="FR gD_12">147.24</div>
<div class="CL"></div>
</div>
<div class="PA7 brdb">
<div class="FL gL_10 UC">DIV (%)</div>
<div class="FR gD_12">1000.00%</div>
<div class="CL"></div>
</div>
<div class="PA7 brdb">
<div class="FL gL_10 UC">Market Lot</div>
<div class="FR gD_12">1</div>
<div class="CL"></div>
</div>
<div class="PA7 brdb">
<div class="FL gL_10 UC">INDUSTRY P/E</div>
<div class="FR gD_12">60.95</div>
<div class="CL"></div>
</div>
</div>

Upvotes: 1

Views: 56

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

Use the text to find the div with "P/E" and get the next div:

price = soup.find("div", class_="FL gL_10 UC", text="P/E").find_next("div").text

If it is always the second div with the css class FR gD_12, you could also just get the first two and extract the second

price = soup.select("div.FR.gD_12", limit=2)[1].text

Upvotes: 4

Related Questions