How can I avoid this error "SyntaxError: unexpected EOF while parsing"

Viewed 1193
while True:
    try:
        result = login(browser, url)
        if not result != 0:
            login(browser, url)
            while True:
                try:
                    time.sleep(1)
                    browser.find_element_by_class_name("submit").click()
                except:
                    browser.find_element_by_xpath("//a[contains(.,'Restart Battle')]").click()

It shows error on this line:

browser.find_element_by_xpath("//a[contains(.,'Restart Battle')]").click()

I tried removing parentheses and spaces and other stuff, but it isn't going off.

Any idea what I should do?

2 Answers

When using try, you need an except. For example, the following code prints error:

try:
    x=1/0
except:
    print("error")

But this throws an SyntaxError: unexpected EOF while parsing:

try:
    x=1/0
# except:
#   print("error")

So, you need an exception at the end of the try statement here:

while True:
    try:
        result = login(browser, url)
        if not result != 0:
        ...
    except:
        ...

This error means that in your script something begins, but the EOF (End of File — the file is your script) occurred before it ends.

(Similar as the unexpected “The End” in a watched crime thriller without revealing a perpetrator.)

It means that you started something (e.g. writing " as a start of the string literal), but you never ended it (no closing ").

The typical cases are unbalanced quotes, apostrophes, parentheses, and so on.

In your case it is the first try: without the expected except: just in the 2nd line of your script.

Related