Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7599793
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T22:44:54+00:00 2026-05-30T22:44:54+00:00

I know that KeyErrors are fairly common with BeautifulSoup and, before you yell RTFM

  • 0

I know that KeyErrors are fairly common with BeautifulSoup and, before you yell RTFM at me, I have done extensive reading in both the Python documentation and the BeautifulSoup documentation. Now that that’s aside, I still haven’t a clue what’s going on with KeyErrors.

Here’s the program I’m trying to run which constantly and consistently results in a KeyError on the last element of the URLs list.

I come from a C++ background, just to let you know, but I need to use BeautifulSoup for work, doing this in C++ would be an imaginable nightmare!

The idea is to return a list of all URLs in a website that contain on their pages links to a certain URL.

Here’s what I got so far:

import urllib
from BeautifulSoup import BeautifulSoup

URLs = []
Locations = []
URLs.append("http://www.tuftsalumni.org")

def print_links (link):
    if (link.startswith('/') or link.startswith('http://www.tuftsalumni')):
        if (link.startswith('/')):
            link = "STARTING_WEBSITE" + link
        print (link)
        htmlSource = urllib.urlopen(link).read(200000)
        soup = BeautifulSoup(htmlSource)
        for item in soup.fetch('a'):
            if (item['href'].startswith('/') or 
                "tuftsalumni" in item['href']):
                URLs.append(item['href'])
            length = len(URLs)
            if (item['href'] == "SITE_ON_PAGE"):
                if (check_list(link, Locations) == "no"):
                    Locations.append(link)



def check_list (link, array):
    for x in range (0, len(array)):
        if (link == array[x]):
            return "yes"
    return "no"

print_links(URLs[0])

for x in range (0, (len(URLs))):
    print_links(URLs[x]) 

The error I get is on the next to last element of URLs:

File "scraper.py", line 35, in <module>
    print_links(URLs[x])
  File "scraper.py", line 16, in print_links
    if (item['href'].startswith('/') or 
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-   packages/BeautifulSoup.py", line 613, in __getitem__
    return self._getAttrMap()[key]
KeyError: 'href'   

Now I know I need to use get() to handle the KeyError default case. I have absolutely no idea how to actually do that, despite literally an hour of searching.

Thank you, if I can clarify this at all please do let me know.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T22:44:55+00:00Added an answer on May 30, 2026 at 10:44 pm

    If you just want to handle the error, you can catch the exception:

        for item in soup.fetch('a'):
            try:
                if (item['href'].startswith('/') or "tuftsalumni" in item['href']):
                (...)
            except KeyError:
                pass # or some other fallback action
    

    You can specify a default using item.get('key','default'), but I don’t think that’s what you need in this case.

    Edit: If everything else fails, this is a barebones version that should be a reasonable starting point:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import urllib
    from BeautifulSoup import BeautifulSoup
    
    links = ["http://www.tuftsalumni.org"]
    
    def print_hrefs(link):
        htmlSource = urllib.urlopen(link).read()
        soup = BeautifulSoup(htmlSource)
        for item in soup.fetch('a'):
            print item['href']
    
    for link in links:
        print_hrefs(link)
    

    Also, check_list(item, l) can be replaced by item in l.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I know that this may be common knowledge, but is there a way to
We know that IPhone has a push notification function. But I have different kinds
we know that we have to previously declare a variable using __block if we
I'm writing some scripts that will be used by non-python users. I have a
I know that lot of questions about HTML sanitizers have appeared in SO, but
I know that I can do something like $int = (int)99; //(int) has a
I know that default cron's behavior is to send normal and error output to
I know that you can insert multiple rows at once, is there a way
I know that |DataDirectory| will resolve to App_Data in an ASP.NET application but is
I know that the MsNLB can be configured to user mulitcast with IGMP. However,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.