-1

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)
Barmar
  • 741,623
  • 53
  • 500
  • 612
Leo Torres
  • 673
  • 1
  • 6
  • 18
  • Don't use `try/catch`. Put the result of `cssselect()` in a variable, and check the length. – Barmar Apr 24 '20 at 13:19
  • `try: ... except IndexError: ...`…?! – deceze Apr 24 '20 at 13:20
  • Does this answer your question? [Is it a good practice to use try-except-else in Python?](https://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else-in-python) – Joe Apr 24 '20 at 14:19
  • Yes, thank you new to site. Just wanted to know what the -1 means for my question. Thank you. Your Idea worked fine. – Leo Torres Apr 24 '20 at 16:03

2 Answers2

0

as barmar said

table = page_parsed.cssselect('table[class="fullview-news-outer"]')
 if len(table) > 0:
      tbl_first = table[0]
Ahmed Abdelhak
  • 239
  • 3
  • 7
  • 1
    Yes Barmar. I used something very similar to your code. As for the try catch block i was using it as an idea i knew I had to but some logic in place to account for missing/bad data. Thank you for the correction however will remember that going forward. – Leo Torres Apr 24 '20 at 18:57
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]
Saad Arshad
  • 1
  • 1
  • 1