Issue
I am writing a Python web scraper that grabs the price of a certain stock. At the end of my program, there are a few print statements to correctly parse the html data so I can grab the stock's price info within a certain HTML span tag. My question is: How do I do this? I have gotten so far as to get the correct HTML span tag. I thought you could simply do a string splice, however the price of the stock is subject to incessant change and I figure this solution would not be conducive for this problem. I recently started using BeautifulSoup, so a little advice would be much appreciated.
import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
# webscraping reference http://altitudelabs.com/blog/web-scraping-with-python-and-beautiful-soup/
my_url = 'https://quotes.wsj.com/GRPS/options'
#opens up a web connection and "downloads"a copy of the desired webpage
uClient = uReq(my_url)
#dumps the information read on the webpade into a variable for later use/parsing
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "lxml")
#find the html location for the price of the stock
#<span id="quote_val">0.0008</span>
all_stock_info = page_soup.find("section",{"class":"sector cr_section_1"})
find_spans = all_stock_info.find("span",{"id":"quote_val"})
price = page_soup.findAll("span",{"id":"quote_val"})
#sanity checks to make sure the scraper is finding the correct info
print(all_stock_info)
print(len(all_stock_info))
print(len(price))
print(price) #this gives me the right span, I just need to be able to parse
#the price of the stock between here (in this case 0.0008) no
#matter what the price is
print(all_stock_info.span)
print(find_spans)
Solution
You can use .find
with .text
function to get your required value.
Ex:
from bs4 import BeautifulSoup
page_soup = BeautifulSoup(html, "lxml")
price = page_soup.find("span",{"id":"quote_val"}).text
print( price )
Output:
0.0008
Answered By - Rakesh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.