Search code examples
python-2.7if-statementweb-scrapingyahoo-finance

Why did the if statement in the loop not work?


I was scraping Yahoo finance and somehow the if condition did not work. What the if was supposed to do was to print the stock price if the stock price was greater than 50, but it printed all the stocks which were above 50 and below 50.

Here is the code:

import urllib2
from bs4 import BeautifulSoup as bs4

list = ["aapl","goog","yhoo"]
i = 0
while i < len(list):
      url = urllib2.urlopen("http://finance.yahoo.com/q?s="+ list[i] +"&q1=1")
      soup = bs4(url,"html.parser")
      for price in soup.find(attrs={'id':"yfs_l84_" + list[i]}):
           if price > 50:
               print price
               i += 1
           else:
               print "failed"
               1 += 1

Why did it print the stock "yahoo", cause "yahoo" is less than 50, no?


Solution

  • Seems to me you've mixed types:

    if price > 50:

    TypeError: unorderable types: NavigableString() > int()

    Use this:

    if float(price) > 50:
       print price