Question

I use the following code:

from bs4 import BeautifulSoup

soup = BeautifulSoup (open("43rd-congress.htm"))

final_link = soup.p.a
final_link.decompose()

trs = soup.find_all('tr')

for tr in trs:
    for link in tr.find_all('a'):
         fulllink = link.get ('href')
         print fulllink #print in terminal to verify results

tds = tr.find_all("td")

try: 
        names = str(tds[0].get_text())
    years = str(tds[1].get_text())
    positions = str(tds[2].get_text())
    parties = str(tds[3].get_text())
    states = str(tds[4].get_text())
    congress = tds[5].get_text()

 except:
    print "bad tr string"
    continue 


    print names, years, positions, parties, states, congress

And I get the following error:

SyntaxError: 'continue' not properly in loop.

Why is that? I have checked indentations and colons. Thanks for your help in advance.

Was it helpful?

Solution

A few things.

First, continue is for use within a while or for loop to tell the loop to skip to the next iteration. Where you've used it, in a try/except block, doesn't work. You might be thinking of pass, but you only need that if you are trying to do something like:

try:
    # Code with potential error
except ErrortoCatch:
    pass

Where you want to have an indented block, but not do anything in it. Here, that means you want to catch the exception, but not do anything about it.

You have some indentation errors and weirdness, like the fact that names is indented an extra level accidentally. This is probably because you have mixed tabs (which expand to 8 spaces) and spaces (which you should be using 4 of). PEP 8 says you should use 4 space to indent, advice you should follow.

What is probably causing your error is your use of a bare except:, which is almost NEVER a good idea. When you are using try/except blocks, you should always know what error you are looking for so you don't accidentally mask a real error when you are just trying to handle some specific exception. Notably, except: also catches stuff like KeyboardInterrupt, which you really, really, don't want to catch.

What I think is happening is one of the operations in your try block is causing an error that makes the variable unprintable for some reason. This could be A LOT of things, so you should specify what error you are trying to handle in your except statement and then figure out what other error is popping up that you need to fix.

Also, you should never have spaces between a function names and its call, e.g. link.get ('href') => link.get('href').

OTHER TIPS

continue is only allowed within a for or while loop. You have put it in the except. I think you may make the wrong indentation or misunderstand continue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top