Skip to content

Instantly share code, notes, and snippets.

@CloudCray
Created November 24, 2014 17:53
Show Gist options
  • Save CloudCray/3245fa8371f89d30b34e to your computer and use it in GitHub Desktop.
Save CloudCray/3245fa8371f89d30b34e to your computer and use it in GitHub Desktop.
Scrape stock price from google finance
# Python 3.4
import urllib
import bs4
def get_stock_price(name):
url = "https://www.google.com/finance"
req = urllib.request.Request(url)
url_full = url + "?" + urllib.parse.urlencode({"q": name})
req = urllib.request.Request(url_full)
resp = urllib.request.urlopen(req)
data = resp.read()
bs = bs4.BeautifulSoup(data)
div_price = bs.find(attrs={"id": "price-panel"})
span_price = div_price.find(attrs={"class": "pr"})
return float(span_price.text.strip())
print(get_stock_price("GOOG"))
@shikhar2402
Copy link

Traceback (most recent call last):

File "", line 1, in
resp = urllib.request.urlopen(req)

File "C:\Users\hp\Anaconda3\lib\urllib\request.py", line 223, in urlopen
return opener.open(url, data, timeout)

File "C:\Users\hp\Anaconda3\lib\urllib\request.py", line 532, in open
response = meth(req, response)

File "C:\Users\hp\Anaconda3\lib\urllib\request.py", line 642, in http_response
'http', request, response, code, msg, hdrs)

File "C:\Users\hp\Anaconda3\lib\urllib\request.py", line 564, in error
result = self._call_chain(*args)

File "C:\Users\hp\Anaconda3\lib\urllib\request.py", line 504, in _call_chain
result = func(*args)

File "C:\Users\hp\Anaconda3\lib\urllib\request.py", line 756, in http_error_302
return self.parent.open(new, timeout=req.timeout)

File "C:\Users\hp\Anaconda3\lib\urllib\request.py", line 532, in open
response = meth(req, response)

File "C:\Users\hp\Anaconda3\lib\urllib\request.py", line 642, in http_response
'http', request, response, code, msg, hdrs)

File "C:\Users\hp\Anaconda3\lib\urllib\request.py", line 570, in error
return self._call_chain(*args)

File "C:\Users\hp\Anaconda3\lib\urllib\request.py", line 504, in _call_chain
result = func(*args)

File "C:\Users\hp\Anaconda3\lib\urllib\request.py", line 650, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)

HTTPError: Forbidden

this error is displayed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment