首页 > 解决方案 > BS 4 在元素中查找元素

问题描述

我想找到网站的一些元素,但只找到某个元素中的元素。然后我想将它们添加到数组中。我做了这个简单的代码,但有些东西不起作用:

beautiful_soup.find_all(element, {'class': 'some-class'})

什么都没有发生,但我确信这有效。一般来说,我会找到所有elementssome-class,然后我想在这个元素中找到其他类的其他元素。我想这样做,因为如果我不这样做并将其添加到数组中,我会得到不同元素的“儿子”元素。当然,我通过设置 bs4 编写了所有无聊的代码,我检查了一下,bs4 正在工作。

网站:亚马逊(搜索选项卡) 例外输出:产品 + 价格

例如:

轨道('macbook')

例外输出:[['Macbook pro', 990], [...]]


谢谢你的帮助

PS。对不起我的英语,我知道这在“技术”描述中特别糟糕。

标签: pythonweb

解决方案


简单的例子 基于一些稀疏的信息......

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&nbsp;GHz dual-core Intel Core&nbsp;i3 Prozessor der 10.&nbsp;Generation, 8&nbsp;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&nbsp;Core&nbsp;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

推荐阅读