0

Basically I'm doing some web scraping with selenium and need to define a variable as one thing if no error occurs, or another thing if an error does occur.

Snippet:

    try:
        raw_cc_timeframe = driver.find_element_by_xpath("//*[@id='nearbyStore']/div/div/div/div/div/div/ul/li[1]/div[1]/p")
        cc_timeframe = raw_cc_timeframe.text
    except NoSuchElementException:
        cc_timeframe = ""

I want the variable named cc_timeframe to be called the name of the element if the element exists, however if it does not, I want the variable to be blank.

I keep getting an unboundlocalerror and really can't figure out why despite reading numerous posts.

I've tried setting the variable to global, however when I run this function hundreds of times, the variables don't seem to reset each time, leading to wrong values.

I'm pretty new to all this so any help would be much appreciated.

user5847481
  • 55
  • 1
  • 6
  • 1
    Possible duplicate of [UnboundLocalError in Python](http://stackoverflow.com/questions/9264763/unboundlocalerror-in-python) – dot.Py Feb 22 '17 at 16:08
  • Please [edit] your this post to show your full code, it doesn't belong in an answer. – SiHa Feb 22 '17 at 19:51

1 Answers1

0

Try setting cc_timeframe="" before doing the search and using pass as the response to the not found exception

try:
    cc_timeframe = "" 
    raw_cc_timeframe = driver.find_element_by_xpath("//*[@id='nearbyStore']/div/div/div/div/div/div/ul/li[1]/div[1]/p")
    cc_timeframe = raw_cc_timeframe.text
except NoSuchElementException:
    pass
CJC
  • 400
  • 4
  • 15
  • Thanks for the prompt reply. Okay now I get a NameError when i try and print cc_timeframe – user5847481 Feb 22 '17 at 16:35
  • 1
    Try setting it as "bob" and re - run please it sounds like you have something else going on. I have assumed that you still have it declared as global, try with and without that option – CJC Feb 22 '17 at 16:47
  • Please find the full function below – user5847481 Feb 22 '17 at 18:09
  • I've solved it. I had the variable within another try/ except block so the variable wasn't being assigned. My mistake – user5847481 Feb 22 '17 at 19:13
  • Thought so, you either used the same name twice for different purposes or outside that function. Pop an accept on the answer when you get the chance please – CJC Feb 23 '17 at 01:15