【问题标题】:BS4 getting value from different div with the same classBS4 从具有相同类的不同 div 中获取价值
【发布时间】:2021-03-25 23:36:35
【问题描述】:

我正在尝试抓取具有两种价格类型的网站,正常价格和折扣价格。

正常价格 HTML:

<p class="plp__price__325EX">
   <span aria-label="$29.99">$29.99</span>
</p>

HTML 折扣价:

<p class="plp__price__325EX plp__salePrice__2ExZ2 plp__price__325EX">
       $11.99 // trying to get this price
       <span class="plp__priceStrikeThrough__2MAlQ plp__price__325EX">$15.99</span>
    </p>

正常价格代码:

try:
    normal_price_element = item.find('p', {'class', 'plp__price__325EX'})
    normal_price = normal_price_element.find('span').text
except:
    normal_price = ''

折扣价代码:

try:
    disc_price = item.find('p', {'class', 'plp__salePrice__2ExZ2'}).text
except:
    disc_price = ''

这些代码 sn-ps 之间的唯一区别是类名。问题是p 类中的跨度包含plp__price__325EX,因此正常价格代码将在不应该运行时运行,并获得正常价格而不是折扣价。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    假设你有这个文件:

    from bs4 import BeautifulSoup
    
    
    html_doc = """
    <p class="plp__price__325EX plp__salePrice__2ExZ2 plp__price__325EX">
           $11.99
           <span class="plp__priceStrikeThrough__2MAlQ plp__price__325EX">$15.99</span>
    </p>
    
    <p class="plp__price__325EX">
       <span aria-label="$29.99">$29.99</span>
    </p>"""
    
    
    soup = BeautifulSoup(html_doc, "html.parser")
    

    然后你可以使用 lambda 函数定位到只包含一个类plp__price__325EX&lt;p&gt; 标签:

    # find <p> tag that contains only *ONE* class="plp__price__325EX"
    normal_price = soup.find(
        lambda tag: tag.name == "p"
        and tag.get("class", []) == ["plp__price__325EX"]
    )
    
    dis_price = soup.find("p", class_="plp__salePrice__2ExZ2")
    
    
    print(normal_price.get_text(strip=True))
    print(dis_price.contents[0].strip())
    

    打印:

    $29.99
    $11.99
    

    或者你可以使用 CSS 选择器:

    normal_price = soup.select_one(
        "p.plp__price__325EX:has(>[aria-label])"
    ).text.strip()
    dis_price = soup.select_one("p.plp__salePrice__2ExZ2").text.split()[0]
    
    print(normal_price)
    print(dis_price)
    

    打印:

    $29.99
    $11.99
    

    【讨论】:

    • 令人印象深刻。你真的很了解你的 BS :>p
    • 哈,我只是想说
    猜你喜欢
    • 2015-02-17
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 2021-01-02
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多