python - Can I return a text value if a certain tag is found? -


i searching following html beautiful soup keywords, when keyword found return text contained in next div class ds_data. in case text 1

this has worked fine, few of divs contain image red x indicate 0. there way of saying if image of class spacer_top n-sign detected treat text value of '0'?

my code

#hdmi pattern = re.compile(r'\s*%s\s*' % 'hdmi ports quantity') hdmi_ports = soup.find(text=pattern).findnext('div',{'class':'ds_data'}).text print hdmi_ports  #dvi ports pattern = re.compile(r'\s*%s\s*' % 'dvi port') dvi_ports = soup.find(text=pattern).findnext('div',{'class':'ds_data'}) print dvi_ports 

html

<div class="tablerow"> <div class="ds_label"> <span class="tip-anchor tip-anchor-text"> hdmi ports quantity</span>ev <span class="red line"> <div class="tooltip-text"> </div> <div class="ds_data"> 1 </div> </div> <div class="tablerow"> <div class="ds_label"> <span class="tip-anchor tip-anchor-text"> dvi port</span>ev <span class="red line"> <div class="tooltip-text"> </div> <div class="ds_data"> <img src="/imgs/spacer.png" class="spacer_top n-sign" alt="yes"/> </div> </div> 

you need check whether <div class="ds_data"> element contains img classes, using find():

for search_text in ('hdmi ports quantity', 'dvi port'):     pattern = re.compile(r'\s*%s\s*' % search_text)     ds_data = soup.find(text=pattern).findnext('div', {'class': 'ds_data'})     if ds_data.find('img', {'class': 'spacer_top n-sign'}):         result_text = '0'     else:         result_text = ds_data.text     print search_text, result_text 

output:

hdmi ports quantity  1  dvi port 0 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -