python - 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)
解决方案
从项目中获取文本:
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 浏览器BeautifulSoup
JavaScript
Selenium
JavaScript
推荐阅读
- firebase - Flutter 用户注册 Firebase:添加额外的用户信息(年龄、用户名)
- c++ - 更新 GrabCut 中 Gibbs 能量的数据项
- excel - 将 VBA 用户表单打印为 PDF
- g++ - GNU C++ 编译器 g++ 的优化级别表,准确吗?
- python - python中具有设定长度的合同词
- fine-uploader - FineUploader 5.14.0 - setParams 不适用于大文件
- caching - 虚拟索引物理标记缓存如何解决同音异义问题?
- django - 如何在 Wagtail CMS 中添加对 ImageChooserBlock 的矢量图像支持?
- java - 在 Tomcat 中为 Spring Boot 应用程序访问 externalize application.properties?
- keras - 在 R 中部署闪亮的应用程序时出现问题。使用带有网状结构的虚拟环境在应用程序中运行 python 代码。错误——虚拟环境:权限被拒绝