joycey joycey - 3 months ago 8
Python Question

Append value to list with BeautifulSoup in Python

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)


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?

Answer

You can use a try, except to catch your exceptions as follows.

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')

Then you will have as much data in your fields as there is available. You can also use a try, except 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 alltel[x], allemail[x] and allname[x] all refer to the same entity.