如何在美丽的汤中获得类似的标签?

时间:2014-02-02 17:05:45

标签: python beautifulsoup

<div id="listing-details">
<div id="listing-details-list">
  <h3 class="listing-details-header">
  <ul class="important-fields">
  <ul>
    <li>
      <span> Property Reference: </span>
      <strong> BLJLT/HSN/02022014/BNJM/DD </strong>
    </li>
    <li>
      <span> Furnished: </span>
      <strong> No </strong>
    </li>
    <li>
      <span> Listed By: </span>
      <strong> Agent </strong>
    </li>
  </ul>
  <ul>
    <li>
      <span> Rent Is Paid: </span>
      <strong> Yearly </strong>
    </li>
    <li>
      <span> Building: </span>
      <strong> Burj Al Nujoom </strong>
    </li>
    <li>
      <span> Amenities: </span>
      <strong> Central A/C & Heating , Balcony , Built in Wardrobes , Security , View of Landmark </strong>
    </li>
    <li id="details-agent-info">
      <span>Listed by:</span>
      <strong>
    </li>
  </ul>
</div>

我希望使用

获取以上所有标签
for a in soup.select("#listing-details-list li span"):
    print spans_others.append(a.text)

但它不起作用。谁能告诉我这是什么问题?我在Python中使用Beautiful Soup。

1 个答案:

答案 0 :(得分:0)

for a in soup.select("#listing-details-list li span"):

此行没有问题,假设您尝试获取span ID下的所有listing-details-list标记。参见:

for a in soup.select("#listing-details-list li span"):
    print a
<span> Property Reference: </span>
<span> Furnished: </span>
<span> Listed By: </span>
<span> Rent Is Paid: </span>
<span> Building: </span>
<span> Amenities: </span>
<span>Listed by:</span>

您的问题是,您正试图print append来电的结果:

print spans_others.append(a.text)

list.append始终返回None(它会改变列表,它不会return任何内容。

a = [].append(4)

a is None
Out[19]: True

因此,在您完成追加后,请先打印spans_others,或print(a)等等。