我试图用Python从coinbase网站中提取比特币价格,但我对HTML不太熟悉。当我检查coinbase网站(https://www.coinbase.com/price/bitcoin)时,我得到了以下内容(这是整个检查的一个片段),我认为可以从以下内容中提取价格:
<div class="cds-flex-f1g67tkn cds-baseline-b1fcn5pa cds-column-ci8mx7v cds-0-_1t4ck38">
<div class="cds-typographyResets-t1xhpuq2 cds-display3-doujgnf cds-foreground-f1yzxzgu cds-transition-txjiwsi cds-start-s1muvu8a cds-tabularNumbers-t11sqpt cds-1-_qem5ui">
<span>£21,976.91</span>
</div>
...
我试着问chatGPT,因为我又不懂HTML,它得出了这样的结果:
import requests
from bs4 import BeautifulSoup
# define the URL of the Coinbase webpage
url = 'https://www.coinbase.com/price/bitcoin'
# make a GET request to the webpage and get the HTML code
response = requests.get(url)
html_code = response.content
# create a BeautifulSoup object and parse the HTML code
soup = BeautifulSoup(html_code, 'html.parser')
# find the element that contains the price data
price_element = soup.find('div', {'class': 'cds-typographyResets-t1xhpuq2 cds-display3-doujgnf cds-foreground-f1yzxzgu cds-transition-txjiwsi cds-start-s1muvu8a cds-tabularNumbers-t11sqpt cds-1-_qem5ui'})
# extract the price data from the element
price_data = price_element.text.strip()
# print the price data
print(price_data)
它抛出了'NoneType'对象没有属性'text'的错误。我相信这是因为soup.find()没有接收任何输入。在做了一些研究和一些试验和错误之后,我似乎无法解决这个问题。你们能帮忙吗?提前感谢!
1条答案
按热度按时间wfypjpf41#
您在页面上看到的数据是用JavaScript从外部URL加载的(所以
beautifulsoup
看不到它)。您可以使用以下示例模拟 AJAX 请求:
图纸: