如何从存储网页代码的变量中提取指定<span>元素的值?
Extracting Bitcoin Price from CoinMarketCap HTML Response
Hey there! I've got you covered on pulling that dynamic Bitcoin price value. Let's break down how to make this work with your existing jQuery code:
Step-by-Step Implementation
The data.contents returned from your API call is the full HTML of the CoinMarketCap page. We can convert this raw HTML into a jQuery object, then use targeted selectors to grab the exact element you need.
Here's the complete updated code snippet:
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('https://coinmarketcap.com/currencies/bitcoin/') + '&callback=?', function(data) { // Turn the raw HTML string into a manipulable jQuery DOM object const $pageContent = $(data.contents); // Target the specific span using combined class + attribute selector const targetPriceElement = $pageContent.find('span.text-large2[data-currency-value]'); // Extract the price text, trimming any extra whitespace const bitcoinPriceText = targetPriceElement.text().trim(); // Optional: Convert text to a numeric value if you need to run calculations const bitcoinPriceNumber = parseFloat(bitcoinPriceText); // Use the price however you need! console.log('Current Bitcoin Price:', bitcoinPriceText); console.log('Price as Numeric Value:', bitcoinPriceNumber); });
Key Details to Keep in Mind
- Selector Accuracy: Using
span.text-large2[data-currency-value]ensures we only match spans that have both the correct class and thedata-currency-valueattribute, avoiding accidental matches with other elements on the page. - Whitespace Cleanup: The
.trim()method removes any leading/trailing spaces that might be hidden in the element's text content. - Page Structure Changes: Heads up—if CoinMarketCap ever updates their page markup (like changing class names or attributes), you'll need to adjust the selector to match the new structure.
内容的提问来源于stack exchange,提问作者marsnebulasoup
相关产品推荐
相关产品推荐

