Python 为什么Beauty soup找不到我要找的html元素?

Python 为什么Beauty soup找不到我要找的html元素?,python,beautifulsoup,Python,Beautifulsoup,我试图通过使用beautiful soup进行解析,从coinbase获取加密货币的价格变化。在coinbase网站上,我可以找到价格变化的html元素 <h4 class="TextElement__Spacer-hxkcw5-0 caIgfs Header__StyledHeader-sc-1xiyexz-0 dLILyj">+0.33%</h4> 数据嵌入在页面内部标记中。您可以使用json模块来解析它 例如: import json import request

我试图通过使用beautiful soup进行解析,从coinbase获取加密货币的价格变化。在coinbase网站上,我可以找到价格变化的html元素

<h4 class="TextElement__Spacer-hxkcw5-0 caIgfs Header__StyledHeader-sc-1xiyexz-0 dLILyj">+0.33%</h4>

数据嵌入在页面内部标记中。您可以使用json模块来解析它

例如:

import json
import requests
from bs4 import BeautifulSoup


url = 'https://www.coinbase.com/price/ethereum'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

data = json.loads(soup.select_one('script#server-app-state').contents[0])

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

print( data['initialData']['data']['prices']['prices']['latestPrice']['percentChange'] )
印刷品:

{'hour': 0.0038781959207123133, 'day': -0.0025064363163135772, 'week': -0.02360650279511788, 'month': 0.13293312491891887, 'year': -0.10963199613423964}
编辑:

行data=json.loadssoup。选择一个“scriptserver-app-state”。内容[0]将:

一,。选择元素。。。从汤里

二,。这个标签的内容是Json字符串,所以我用

三,。结果存储到python字典中的变量数据中


行print data['initialData']['data']['prices']['prices']['latestPrice']['percentChange']将只打印此词典中的一个内容。您可以通过取消对行printjson.dumpsdata的注释来查看此词典的完整内容,indent=4

这是否回答了您的问题?您好,不过这很有效,因为我不熟悉实用的汤和html格式。如果您能解释行data=json.loadssup.select'scriptserver-app-state'。contents[0]和print data['initialData']['data']['prices']['prices']['latestPrice']['percentChange']那就太好了。提前谢谢
{'hour': 0.0038781959207123133, 'day': -0.0025064363163135772, 'week': -0.02360650279511788, 'month': 0.13293312491891887, 'year': -0.10963199613423964}