简体   繁体   中英

Need a try catch block

The function below works fine except if it scans the page and finds the tag "fullview-news-outer" does not exists. This produces the error "list index out of range" . How can I do a try catch to make sure tag "fullview-news-outer" exists and if it does not exit else set the table variable accordingly.

def get_news2(ticker):
    """
    Returns a list of sets containing news headline and url
    """
    page_parsed, _ = http_request_get(url=STOCK_URL, payload={'t': ticker}, parse=True)
    table = page_parsed.cssselect('table[class="fullview-news-outer"]')[0]
    ...
    return (df)

as barmar said

table = page_parsed.cssselect('table[class="fullview-news-outer"]')
 if len(table) > 0:
      tbl_first = table[0]

You can solve the problem without try-catch

page_parsed, _ = http_request_get(url=STOCK_URL, payload={'t': ticker}, parse=True) 
selected = page_parsed.cssselect('table[class="fullview-news-outer"]')
if selected:
    table = selected[0]

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