-1

My bot uses Beautiful soup to parse HTML, and also prints out the web page title of a link said in IRC. This all works except for one thing: If someone gives a dead/fake link, the bot crashes.

The link grabber triggers when "http" is found, so for example if someone just said "http", it crashes because there's no response. Does anyone know how to fix this?

Here's the part of the code that grabs the link and get's the web page title and posts it:

msg_split = msg.split(' ')
for item in msg_split:
    if re.search('^http.*', item, re.I):
        link = item
        if item.find(','):
            link = link.replace(',', ' ')
            soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(link))
            link_title = soup.title.string
            ircSend('PRIVMSG ' + args[2] + ' ' + link_title)
ashastral
  • 2,818
  • 1
  • 21
  • 32
John Garza
  • 94
  • 3
  • 12

1 Answers1

0

Wrap the soup = ... through ircSend(... lines in a try/except statement.

try:
    soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(link))
    link_title = soup.title.string
    ircSend('PRIVMSG ' + args[2] + ' ' + link_title)
except IOError:
    pass
ashastral
  • 2,818
  • 1
  • 21
  • 32
  • Are you using urllib specifically or another URL library via something like `import urllib2 as urllib`? IOError is the only error urllib should return, but you can try changing the 'except' line to just `except:` by itself. – ashastral Jul 28 '12 at 02:42
  • Does the bot give you any information about the crash, like a traceback printed to the console? – ashastral Jul 28 '12 at 02:59
  • Alright, now it doesn't crash, but now it doesn't send the title in the IRC. – John Garza Jul 28 '12 at 03:24
  • Did the bot give you a traceback when it crashed? What did you change that made it not crash? – ashastral Jul 28 '12 at 03:28
  • It didn't give any traceback. The error that I fixed is that there was some conflicting variables if there was no link – John Garza Jul 28 '12 at 03:36
  • Oh, I see what was going wrong. That was partially my fault; I've updated my code snippet above, can you check if that works? – ashastral Jul 28 '12 at 03:40
  • Can you post whatever code you're currently attempting to run? The syntax error could indicate a couple of different things. – ashastral Jul 28 '12 at 04:06
  • I got it, there was a spacing issue. Everything is now working as intended. Thank you for the help! – John Garza Jul 28 '12 at 04:08