Append value to list with BeautifulSoup in Python
<pre><code>allname = []
alltel = []
allemail = []

for link in docdetail:
            name = soup.h1.contents[1]
            tel = soup.find('a', class_='tel').string
            email = soup.find('a', class_='email').string
            allname.append(name)
            alltel.append(tel)
            allemail.append(email)
</code></pre>

<p>I want to append name to allname, tel to alltel, email to allemail after every for loop. But it is possible that the returned value for name/tel/email is empty, then he order of attributes may mess up. 
I want to assign "NA" to the variable if the returned values are empty. How should I write a code for this precisely?</p>

<p>soup.find() returns a None value if there is no match. An attribute error occurs when applying the .string method to a None value. You can catch it this way:</p>

<pre><code>allname = []
alltel = []
allemail = []

for link in docdetail:
            name = soup.h1.contents[1]
            tel = soup.find('a', class_='tel').string
            email = soup.find('a', class_='email').string

            try:
                allname.append(name)
            except AttributeError:
                allname.append(None)

            try:
                allemail.append(name)
            except AttributeError:
                allemail.append(None)

            try:
                allname.append(name)
            except AttributeError:
                allname.append(None)
</code></pre>

python beautifulsoup append