M
M
mekkas1112021-12-08 08:37:22
Python
mekkas111, 2021-12-08 08:37:22

How not to output result with IndexError?

If all the fields on the site are filled, then the result is:

Login: c4actbe011
Name: Yulia Baeva
City: Tula
Birthdate: 1986-09-17

But if something is missing, or the page is not found (404), then the error is: IndexError: list index out of range

It is necessary that only those fields that are on the site are displayed, an example with this profile:
( https://skypli.com/profile/live:remcoschuman )

Login: live:remcoschuman
Name: Putin

import requests
from bs4 import BeautifulSoup
profile = requests.get(f'https://skypli.com/profile/live:remcoschuman')
profile_soup = BeautifulSoup(profile.content, 'lxml')
profile_info = profile_soup.findAll('div', {'class': 'profile-box__table-value'})

profile_name = profile_info[1].text.strip()
profile_city = profile_info[2].text.strip()
profile_birthdate_result = profile_info[4].text.strip()
profile_birthdate = profile_birthdate_result.replace("-",".")
print(f'Login: {username}\nName: {profile_name}\nCity: {profile_city}\nBirthdate: {profile_birthdate_result}')


How can I do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-12-08
@mekkas111

Obviously add a conditional that checks the length of the list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question