【问题标题】:get text between 2 div tags in python在python中获取2个div标签之间的文本
【发布时间】:2020-11-30 21:26:53
【问题描述】:

我正在制作一个从多个站点获取比特币价格的脚本,在其中一个站点上,文本位于 2 个 div 标签之间。

我尝试了多种解决方案,但都没有奏效, 但是我发现了同样的问题here,这正是我需要的,但是在 python 中

注意:网站上的文字每 2 秒更新一次

这是我需要得到的

<div data-bn-type="text" class="css-g80xfv" style="direction: ltr;">$19,490.20</div>
                                                                   ^^^^^^^^^^^

网站 - https://www.binance.com/en

Xpath - //*[@id="__APP"]/div[2]/main/div/div[4]/div/a[2]/div[2]/div

我知道这个网站上有一个 API,但我只想知道价格

谢谢

【问题讨论】:

标签: python


【解决方案1】:

我认为您可能需要使用selenium,因为该页面上的实际价格信息是动态加载的,这是一个每隔2 秒更新一次的示例:

import time
from bs4 import BeautifulSoup
from decimal import Decimal
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

BASE_URL = 'https://www.binance.com/en'
BITCOIN_HREF = '/en/trade/BTC_BUSD'
LAST_PRICE_COLUMN_CLASS = 'css-g80xfv'
WAIT_SECONDS = 2

def main():
    driver = webdriver.Chrome(ChromeDriverManager().install())

    for _ in range(5): # replace with `while True:` if you want to get updates "indefinitely"
        driver.get(BASE_URL)

        time.sleep(WAIT_SECONDS)

        html = driver.page_source
        soup = BeautifulSoup(html, 'html.parser')
    
        btc_a_tag = soup.find('a', href=BITCOIN_HREF)
        btc_price_string = btc_a_tag.find('div', class_=LAST_PRICE_COLUMN_CLASS).text
        btc_price_decimal = Decimal(btc_price_string.strip('$').replace(',', ''))
        print(f"btc_price_string={btc_price_string}, btc_price_decimal={btc_price_decimal}")

    driver.close()

if __name__ == '__main__':
    main()

示例输出:

btc_price_string=$19,306.29, btc_price_decimal=19306.29
btc_price_string=$19,307.85, btc_price_decimal=19307.85
btc_price_string=$19,308.18, btc_price_decimal=19308.18
btc_price_string=$19,308.41, btc_price_decimal=19308.41
btc_price_string=$19,308.18, btc_price_decimal=19308.18

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-26
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2016-12-28
    • 1970-01-01
    相关资源
    最近更新 更多