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>You can use a <code>try, except</code> to catch your exceptions as follows.</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
        allname.append(name)
        try:
            alltel.append(tel)
        except:
            alltel.append('N/A')
        try:
            allemail.append(email)
        except:
            allemail.append('N/A')
</code></pre>

<p>Then you will have as much data in your fields as there is available. You can also use a <code>try, except</code> for the name if it not certain that it is there. This way will preserve your data in the same index - that is that entry <code>alltel[x]</code>, <code>allemail[x]</code> and <code>allname[x]</code> all refer to the same entity.</p>

python beautifulsoup append