python - BS 4 在元素中查找元素
问题描述
我想找到网站的一些元素,但只找到某个元素中的元素。然后我想将它们添加到数组中。我做了这个简单的代码,但有些东西不起作用:
beautiful_soup.find_all(element, {'class': 'some-class'})
什么都没有发生,但我确信这有效。一般来说,我会找到所有elements
的some-class
,然后我想在这个元素中找到其他类的其他元素。我想这样做,因为如果我不这样做并将其添加到数组中,我会得到不同元素的“儿子”元素。当然,我通过设置 bs4 编写了所有无聊的代码,我检查了一下,bs4 正在工作。
网站:亚马逊(搜索选项卡) 例外输出:产品 + 价格
例如:
轨道('macbook')
例外输出:[['Macbook pro', 990], [...]]
谢谢你的帮助
PS。对不起我的英语,我知道这在“技术”描述中特别糟糕。
解决方案
简单的例子 基于一些稀疏的信息......
from bs4 import BeautifulSoup
data = """
<div data-asin="B0863ZJ1T3" data-index="1" data-uuid="47d184c2-ea2c-4758-95ce-d34d2ed6dc71" data-component-type="s-search-result" class="sg-col-20-of-24 s-result-item s-asin sg-col-0-of-12 sg-col-28-of-32 sg-col-16-of-20 AdHolder sg-col sg-col-32-of-36 sg-col-12-of-16 sg-col-24-of-28" data-component-id="8" data-cel-widget="search_result_1">
<span class="a-price-whole">999,00</span>
<span class="a-size-medium a-color-base a-text-normal" dir="auto">Apple MacBook Air (13", 1,1 GHz dual-core Intel Core i3 Prozessor der 10. Generation, 8 GB RAM, 256 GB) - Gold (Vorgängermodell)</span>
</div>
<div data-asin="B081FZHSLZ" data-index="2" data-uuid="2c44727b-46a2-45d0-b06a-e95f4bec3bd9" data-component-type="s-search-result" class="sg-col-20-of-24 s-result-item s-asin sg-col-0-of-12 sg-col-28-of-32 sg-col-16-of-20 AdHolder sg-col sg-col-32-of-36 sg-col-12-of-16 sg-col-24-of-28" data-component-id="12" data-cel-widget="search_result_2">
<span class="a-size-medium a-color-base a-text-normal" dir="auto">Neues Apple MacBook Pro (16", 16GB RAM, 512GB Speicherplatz, 2,6GHz Intel Core i7) - Silber</span>
<span class="a-price-whole">2.287,23</span>
</div>
"""
soup = BeautifulSoup(data, "html.parser")
elements = soup.find_all('div', attrs={'data-component-type':'s-search-result'})
for element in elements:
title = element.find('span', class_='a-size-medium a-color-base a-text-normal').getText()
price = element.find('span', class_='a-price-whole').getText()
print(title, price)
输出
Apple MacBook Air (13", 1,1 GHz dual-core Intel Core i3 Prozessor der 10. Generation, 8 GB RAM, 256 GB) - Gold (Vorgängermodell) 999,00
Neues Apple MacBook Pro (16", 16GB RAM, 512GB Speicherplatz, 2,6GHz Intel Core i7) - Silber 2.287,23
推荐阅读
- c++ - 使用 cmake-gui 工具在 Windows 上安装 mFast
- windows - 是否可以在没有 Microsoft Store 的情况下在 Windows 10 WSL 中安装 Ubuntu?
- mysql - 使用一条 SQL 语句用相应的数据更新单个列的所有行
- matlab - 如何将一系列 jpeg 数据从 MATLAB 传递到 ffplay
- kubernetes - 有没有办法在特定的 resourceVersion 检索 kubernetes 资源?
- angular - 我无法显示默认 Angular2 的选项
- java - Apache Spark JavaRDD 按 2 个字段分组并获取自定义类型对象的第三个字段的总和
- c# - 使用 Google Cloud Vision 检测 PDF/TIFF 文件中的文本
- javascript - 如何在 draw.io 中创建新图像并从我的网站中保存它的数据库?
- java - Spring Boot 在迁移到 JDK 11 后由于 Hibernate 错误而失败