如何抓取特定的Tex

2024-04-24 11:21:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从这个网站获取比特币的价格: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


Tags: httpsimportcomdatavaluewwwcontentfind
3条回答

内容动态地来自返回json的API调用。您可以使用货币列表或单一货币。有了requests,javascript就不会运行,这个内容也不会添加到DOM中,各种DOM更改也就不会发生了。你知道吗

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)

您的网站没有以html格式保存数据,这样您就无法刮取数据,但它们使用的是您可以使用的终结点:

data = requests.get('https://production.api.coindesk.com/v1/currency/ticker?currencies=BTC').json()
p_value = data['data']['currency']['BTC']['quotes']['USD']['price']
print(p_value)

# output: 11375.678380772

价格一直在变化,所以我的产量可能不同

这里的问题是soup.find()调用没有返回值(也就是说,页面上定义的属性没有span),因此当您尝试获取data-value时,没有字典可供查找。你知道吗

相关问题 更多 >