首页 > 解决方案 > bs4 中 .find() 的正确语法是什么?

问题描述

我正在尝试从 coinbase 中获取比特币价格,但找不到正确的语法。当我运行程序(不带问号的行)时,我得到了我需要的 html 块,但我不知道如何缩小和检索价格本身。任何帮助表示赞赏,谢谢。

    import requests
    from bs4 import BeautifulSoup

    url = 'https://www.coinbase.com/charts'
    data = requests.get(url)
    nicedata = data.text

    soup = BeautifulSoup(nicedata, 'html.parser')
    prettysoup = soup.prettify()


    bitcoin = soup.find('h4', {'class': 
    'Header__StyledHeader-sc-1q6y56a-0 hZxUBM 
    TextElement__Spacer-sc-18l8wi5-0 hpeTzd'})

    price = bitcoin.find('???')

    print(price)        

附件图片包含html

标签: pythonhtmlcsssyntaxbeautifulsoup

解决方案


从项目中获取文本:

price = bitcoin.text

但是这个页面有很多<h4>这个类的项目,但find()只有第一个,它有文本Bitcoin,而不是你的图像中的价格。您可能需要find_all()获取所有项目的列表,然后您可以使用索引[index]或切片[start:end]来获取一些项目,或者您可以使用for-loop 来处理列表中的每个项目。

import requests
from bs4 import BeautifulSoup

url = 'https://www.coinbase.com/charts'
r = requests.get(url)

soup = BeautifulSoup(r.text, 'html.parser')

all_h4 = soup.find_all('h4', {'class': 'Header__StyledHeader-sc-1q6y56a-0 hZxUBM TextElement__Spacer-sc-18l8wi5-0 hpeTzd'})

for h4 in all_h4:
    print(h4.text)

如果将数据保存在列表或数组或 DataFrame 的列表中,则可以更轻松地处理数据。<tr>但是要创建列表列表,查找行和在每行搜索中会更容易<h4>

import requests
from bs4 import BeautifulSoup

url = 'https://www.coinbase.com/charts'
r = requests.get(url, headers=headers)

soup = BeautifulSoup(r.text, 'html.parser')

all_tr = soup.find_all('tr')

data = []

for tr in all_tr:
    row = []
    for h4 in tr.find_all('h4'):
        row.append(h4.text)
    if row: # skip empty row
        data.append(row)

for row in data:
    print(row)

它不需要class全部获取h4


顺便说一句:JavaScript当您滚动页面但无法运行时requests,此页面用于附加新行- 因此,如果您需要所有行,那么您可能需要控制运行的 Web 浏览器BeautifulSoupJavaScriptSeleniumJavaScript


推荐阅读