Skip to main content
 首页 » 编程设计

python之如何抓取特定文本

2024年11月01日18softidea

我想从这个网站上获取比特币的价格:https://www.coindesk.com/price/bitcoin 但我不确定该怎么做,我对编码还很陌生。

到目前为止,这是我的代码,我不确定我做错了什么。提前致谢。

from bs4 import BeautifulSoup 
import requests 
 
r = requests.get('https://www.coindesk.com/price/bitcoin') 
r_content = r.content 
soup = BeautifulSoup(r_content, 'lxml') 
 
p_value = soup.find('span', {'class': "currency-price", "data-value": True})['data-value'] 
 
print(p_value) 
 
 

这是结果:

Traceback (most recent call last): File "C:/Users/aidan/PycharmProjects/scraping/Scraper.py", line 8, in p_value = soup.find('span', {'class': "currency-price", "data-value": True})['data-value'] TypeError: 'NoneType' object is not subscriptable

请您参考如下方法:

内容是从返回 json 的 API 调用动态获取的。您可以使用货币列表或单一货币。对于 requests,javascript 不会运行,并且此内容不会添加到 DOM 和各种 DOM 更改,以保留在浏览器中看到的 html,不会发生。

import requests 
 
r = requests.get('https://production.api.coindesk.com/v1/currency/ticker?currencies=BTC').json() 
print(r) 
price = r['data']['currency']['BTC']['quotes']['USD']['price'] 
print(price) 
r = requests.get('https://production.api.coindesk.com/v1/currency/ticker?currencies=ADA,BCH,BSV,BTC,BTG,DASH,DCR,DOGE,EOS,ETC,ETH,IOTA,LSK,LTC,NEO,QTUM,TRX,XEM,XLM,XMR,XRP,ZEC').json() 
print(r)