【问题标题】:What is the proper syntax for .find() in bs4?bs4 中 .find() 的正确语法是什么?
【发布时间】:2019-12-02 03:53:41
【问题描述】:

我正在尝试从 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)        

The attached image contains the html

【问题讨论】:

  • price = bitcoin.text
  • 这个类有很多<h4> - find() 只得到第一个,它有文字Bitcoint,而不是你的图片价格。您可能需要find_all() 才能将所有项目作为列表。稍后for-loop 检查列表中的每个元素以获得预期值。
  • 获取行<tr> 和稍后在行搜索<h4> 可能更容易。这样,您可以在列表或 numpy.array 或 pandas.DataFrame 列表中组织数据
  • 阅读 BeautifulSoup 文档,它们在 IMO 方面非常出色。您在寻找 BeautifulSoup 的指南吗?

标签: python html css syntax beautifulsoup


【解决方案1】:

从项目中获取文本:

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)

获取所有h4 不需要class


顺便说一句: 当您滚动页面时,此页面使用 JavaScript 追加新行,但 requestsBeautifulSoup 无法运行 JavaScript - 所以如果您需要所有行,那么您可能需要Selenium 来控制运行JavaScript 的网络浏览器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-19
    • 2018-11-14
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2014-08-04
    相关资源
    最近更新 更多