To get/strip the text from the below html part, I have parsed the page and taken in to a variable.
From that variable, i have scoped down to these particular divs to another variable called items. Now to strip the text(phone number in this case), I have used the list comprehension with for loop like, phone = [item.find(class_='phone').get_text() for item in items]
<div class="description">
<div class="phone">
<a href="tel:(000) 000 -0000" title="call (000) 000 -0000">
(000) 000 -0000
</a>
</div>
<div class="description">
<div class="phone">
<a href="tel:(111) 111 -1111" title="call (111) 111 -1111">
(111) 111 -1111
</a>
</div>
So i'm getting the result what i expected. Just those phone numbers in the Result. ['(000) 000 -0000','(111) 111 -1111']
My Problem is, When there is no phone number in the page under any of the div. I get the error "AttributeError: 'NoneType' object has no attribute 'get_text'"
I know why we are getting this error. When the result returns as none, It throws an error that it cannot find a get_text attribute for none. I have gone through other articles for this error in Stackoverflow but didn't want to use the try except method instead I want to finish this is in single line.
This is what i'm thinking to do,
Running the command, phone = [item.find(class_='phone') for item in items] will get me something like below.
[None, <div class="phone"> <a href="tel:(000) 000-0000" title="call (000) 000-0000">(000) 000-0000</a> </div>, <div class="phone"> <a href="tel:(111) 111-1111" title="call (111) 111-1111">(111) 111-1111</a> </div>
After this, can we do a combination of if else and for loop together in a single line to strip the phone numbers and print "None" as it is if the list element has "None" value.
Trying something like this, phone = [item='None' if item=='None' else item.find(class_='phone').get_text() for item in items] However, I'm not getting the results. Any help is appreciated.
Referred article, One-line list comprehension: if-else variants and Python for and if on one line