Jordan_m23
Jordan_m23

Reputation: 5

Get value using getElementsbyClassName

I have been using this function to get value of a stock price from Yahoo! Finance:

html.getElementsByClassName("Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").Item(0).innerText

The website that I use is (example ticker IQ): https://finance.yahoo.com/quote/?p=IQ

But recently, maybe due to an upgrade, this class throws up an error. Running through the html variable I find that now it's renamed as: ("Fw(b) Fz(36px) Mb(-4px) D(ib)").

I have the full text here, I just want to know how can I get the value of the ticker from this element.

    <DIV class="D(ib) Mend(20px)" data-reactid="52">
        <FIN-STREAMER class="Fw(b) Fz(36px) Mb(-4px) D(ib)" data-reactid="53" active="" value="4.71" data-trend="none" data-field="regularMarketPrice" data-symbol="IQ" data-test="qsp-price" data-pricehint="4">
            4.7100
        </FIN-STREAMER>
        <FIN-STREAMER class="Fw(500) Pstart(8px) Fz(24px)" data-reactid="54" active="" value="-0.8800001" data-trend="txt" data-field="regularMarketChange" data-symbol="IQ" data-test="qsp-price-change" data-pricehint="4">
            <SPAN class=C($negativeColor)>-0.8800</SPAN>
        </FIN-STREAMER>
        <!-- react-text: 55 -->
        <!-- /react-text -->
        <FIN-STREAMER class="Fw(500) Pstart(8px) Fz(24px)" data-reactid="56" active="" value="-0.15742399" data-trend="txt" data-field="regularMarketChangePercent" data-symbol="IQ" data-template="({fmt})" data-pricehint="4">
            <SPAN class=C($negativeColor)>(-15.74%)</SPAN>
        </FIN-STREAMER>
        <FIN-STREAMER class=D(n) data-reactid="57" active="true" value="" data-trend="none" data-field="regularMarketTime" data-symbol="IQ" changeev="regularTimeChange">
        </FIN-STREAMER>
        <FIN-STREAMER class=D(n) data-reactid="58" active="true" value="" data-trend="none" data-field="marketState" data-symbol="IQ" changeev="marketState">
        </FIN-STREAMER>

The value I want to get out is 4.7100.

What I'm using is:

html.getElementsByClassName("Fw(b) Fz(36px) Mb(-4px) D(ib)").Item(0).innerText

But this returns an empty result.

Upvotes: 0

Views: 614

Answers (1)

QHarr
QHarr

Reputation: 84465

Move away from dynamic classes as these are prone to break and instead look for stable attributes/relationships between elements. I would have the following:

html.querySelector("#quote-header-info [data-field=regularMarketPrice]").innerText

This uses the id quote-header-info to anchor a parent reducing the matches within the following selectors to one. The space before the [data-field=regularMarketPrice] is a descendant combinator specifying what follows is a descendant element in the DOM. The [data-field=regularMarketPrice] is an attribute = value css selector targeting the desired node by its data-field attribute and associated value.

Upvotes: 3

Related Questions