首页 文章

BeautifulSoup匹配不正确的类

提问于
浏览
0

我正在使用如下所示的HTML:

<td class="hidden-xs BuildingUnit-price" data-sort-value="625000">
<span class="price">$625,000  </span>
</td>
<td class="hidden-xs BuildingUnit-bedrooms" data-sort-value="4.0">
        4 rooms, 2 beds
      </td>
<td class="hidden-xs BuildingUnit-bathrooms">
        5 baths
      </td>
<td class="hidden-xs" data-sort-value="1">
    1 bath
  </td>

我编写了下面的脚本来识别具有类“hidden-xs”的td标签,以便拉出房地产列表的浴室数量,但它也匹配“hidden-xs BuildingUnit-price”类 . 我怎么能纠正这个?

#Extract the number of baths
import re
lst_baths=list()
baths=soup.find_all("td", class_=["hidden-xs"])  
bath_lines=[td.get_text().strip() for td in baths]
pattern=re.compile(r'(\d{1})\D*(bath|baths)$')
for bath in bath_lines:
    match=pattern.match(bath)
    if match:
        lst_baths.append(bath.split()[0])

例如,正如它目前所写,我的代码选择了“5个浴室”系列,但我只想要它拿起“1浴”系列 .

1 回答

  • 0

    找到了测试每场比赛的类的方法:

    #Extract the baths
    lst_baths=list()
    temp_lst=list()
    baths=soup.find_all("td", class_=["hidden-xs"])
    for item in baths:
        if item['class']==['hidden-xs']:
            temp_lst.append(item)
        else:
            pass
    bath_lines=[td.get_text().strip() for td in temp_lst]
    pattern=re.compile(r'(\d{1})\D*(bath|baths)$')
    for bath in bath_lines:
        match=pattern.match(bath)
        if match:
            lst_baths.append(bath.split()[0])
    

相关问题