简体   繁体   English

python 嵌套标签(美汤)

[英]python nested Tags (beautiful Soup)

I used beautiful soup using python to get data from a specific website but I don't know how to get one of these prices but I want the price in gram (g) AS shown below this is the HTML codeL:我使用了漂亮的汤,使用 python 从特定网站获取数据,但我不知道如何获得其中一个价格,但我想要以克 (g) 为单位的价格,如下所示,这是 HTML 代码:

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

I use this code:我使用这段代码:

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

my result was: 16,000 LL/200g 79,999 LL/Kg我的结果是: 16,000 LL/200g 79,999 LL/Kg

but i want to have: 16,000 LL/200g only但我想拥有:仅 16,000 LL/200g

You will need to first decompose the span inside the div element:您需要首先分解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

Try using soup.select_one('div.promoPrice').contents[0]尝试使用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)

Prints印刷

 16,000 LL/200g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM