如何查找具有特定值的文本BeautifulSoup python2.7

时间:2016-03-05 10:09:11

标签: python html beautifulsoup

我有以下html:我试图将以下数字保存为变量立即可用,7,148.49,HatchBack,Good。我遇到的问题是我不能独立地将它们拉出来,因为它们没有附加课程。我想知道如何解决这个问题。以下是html然后我的徒劳代码来解决这个问题。

</div>
<div class="car-profile-info">
<div class="col-md-12 no-padding">
<div class="col-md-6 no-padding">
<strong>Status:</strong> <span class="statusAvail">  Available Now </span><br/>
<strong>Min. Booking </strong>7 Days ($148.89)<br/>
<strong>Style: </strong>Hatchback<br/>
<strong>Transmission: </strong>Automatic<br/>
<strong>Condition: </strong>Good<br/>
</div>

Python 2.7代码: - 这给了我整个HTML!

soup=BeautifulSoup(html)
print soup.find("span",{"class":"statusAvail"}).getText()
for i in soup.select("strong"):
    if i.getText()=="Min. Booking ":
        print i.parent.getText().replace("Min. Booking ","")

2 个答案:

答案 0 :(得分:1)

您可以使用“.next_sibling”导航到您想要的文字:

for i in soup.select("strong"):
   if i.get_text(strip=True) == "Min. Booking":
       print(i.next_sibling) #this will print: 7 Days ($148.89)

另见http://www.crummy.com/software/BeautifulSoup/bs4/doc/#going-sideways

答案 1 :(得分:1)

使用div查找class="car-profile-info"元素下的所有强元素,对于找到的每个元素,获取.next_siblings,直到遇到br元素:

from bs4 import BeautifulSoup, Tag

for strong in soup.select(".car-profile-info strong"):
    label = strong.get_text()
    value = ""
    for elm in strong.next_siblings:
        if getattr(elm, "name") == "br":
            break
        if isinstance(elm, Tag):
            value += elm.get_text(strip=True)
        else:
            value += elm.strip()

    print(label, value)