gpt4 book ai didi

python - bs4 中 .find() 的正确语法是什么?

转载 作者:行者123 更新时间:2023-11-27 22:58:12 25 4
gpt4 key购买 nike

我正试图从 coinbase 中提取比特币价格,但找不到正确的语法。当我运行程序(没有带问号的行)时,我得到了我需要的 html block ,但我不知道如何缩小范围并检索价格本身。感谢任何帮助,谢谢。

    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()只得到第一个,它有文本 Bitcoin ,而不是您图片中的价格。您可能需要 find_all()获取包含所有元素的列表,然后您可以使用索引 [index]或切片 [start:end]得到一些元素,或者你可以使用 for - 循环处理列表中的每个元素。

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当你滚动页面时添加新行但是requestsBeautifulSoup无法运行 JavaScript - 因此,如果您需要所有行,那么您可能需要 Selenium控制运行 JavaScript 的网络浏览器

关于python - bs4 中 .find() 的正确语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59132449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com