簡體   English   中英

python 嵌套標簽(美湯)

[英]python nested Tags (beautiful Soup)

我使用了漂亮的湯,使用 python 從特定網站獲取數據,但我不知道如何獲得其中一個價格,但我想要以克 (g) 為單位的價格,如下所示,這是 HTML 代碼:

<div class="promoPrice margBottom7">16,000 
L.L./200g<br/><span class="kiloPrice">79,999 
L.L./Kg</span></div>

我使用這段代碼:

p_price = product.findAll("div{"class":"promoPricemargBottom7"})[0].text

我的結果是: 16,000 LL/200g 79,999 LL/Kg

但我想擁有:僅 16,000 LL/200g

您需要首先分解div元素內的跨度:

from bs4 import BeautifulSoup

h = """
<div class="promoPrice margBottom7">16,000 L.L./200g<br/>
<span class="kiloPrice">79,999 L.L./Kg</span></div>
"""

soup = BeautifulSoup(h, "html.parser")
element = soup.find("div", {'class': 'promoPrice'})
element.span.decompose()
print(element.text)
#16,000 L.L./200g

嘗試使用soup.select_one('div.promoPrice').contents[0]

from bs4 import BeautifulSoup

html = """<div class="promoPrice margBottom7">16,000 L.L./200g<br/>
<span class="kiloPrice">79,999 L.L./Kg</span></div>"""

soup = BeautifulSoup(html, features='html.parser')

# value = soup.select('div.promoPrice > span')  # for 79,999 L.L./Kg
value = soup.select_one('div.promoPrice').contents[0]
print(value)

印刷

 16,000 LL/200g

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM