There are two possible approaches
One approach is EAFP - Easier to ask for forgiveness than permission
Note the try/except block to handle the error
In this case check what you work with
One approach is EAFP - Easier to ask for forgiveness than permission
Note the try/except block to handle the error
import requests import time from bs4 import BeautifulSoup UID_start = 58217 UID_end = 58221 for UID in range(UID_start, UID_end): print UID page = requests.get("http://forum.shipspotting.com/index.php?action=profile;u=" + str(UID)) #I have altered the link for this post to work soup = BeautifulSoup(page.content, 'html.parser') div = soup.find("div", {'class':'content'}) signature = div.find("div", {'class':"signature"}) user = div.find('tr', {'class':'titlebg'}).find('td').text.split(' ')[-1].strip() try: print('User: {}\nSigniture: {}'.format(user, signature.text)) except AttributeError: print(div.find('tr', {'class':'windowbg'}).text.strip()) print time.sleep(1) # add some sleep between requestsThe otehr one is LBYL - Look before you leap
In this case check what you work with
import requests import time from bs4 import BeautifulSoup UID_start = 58217 UID_end = 58221 for UID in range(UID_start, UID_end): print UID page = requests.get("http://forum.shipspotting.com/index.php?action=profile;u=" + str(UID)) #I have altered the link for this post to work soup = BeautifulSoup(page.content, 'html.parser') div = soup.find("div", {'class':'content'}) signature = div.find("div", {'class':"signature"}) if signature is not None: user = div.find('tr', {'class':'titlebg'}).find('td').text.split(' ')[-1].strip() print('User: {}\nSigniture: {}'.format(user, signature.text)) else: print(div.find('tr', {'class':'windowbg'}).text.strip()) print time.sleep(1) # add some sleep between requestsin both cases the output is
Output:58217
User: nikond3100cam2
Signiture: <a href="http://www.nikon-d3100.com">Nikon D3100</a> - Digital Camera
D3100 NikonNikon DSLR D3100Nikon D3100Nik
58218
User: alvinswaim
Signiture:
58219
The user whose profile you are trying to view does not exist.
58220
The user whose profile you are trying to view does not exist.