简体   繁体   中英

Python: How do I define a variable based on whether an error occurs or not?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM