【问题标题】:beautifulsoup returning data as None that includes <br> tagbeautifulsoup 将包含 <br> 标签的数据返回为 None
【发布时间】:2012-02-01 06:35:50
【问题描述】:

我有一个这样的表格数据:

<table class="tablesorter" id="dea">
<thead>
<tr>
<th class="header ">Name</th>
<th class="header">City</th>
<th class="">Address</th>
<th class="">Phone Nos</th>
<th class="">Email</th>
<th class="">Fax</th>
</tr>
</thead>
<tbody>

<tr class="info">
<td style="font:bold 12px Tahoma; color:#1f2c48;">Audi California</td>
<td>&nbsp;California&nbsp;</td>
<td align="left">
A?85, bay Area, Phase 1, <br>
California<br>
California
- 6554655
</td>
<td align="right">
<br>4747744747<br>108388383
</td>
<td align="center">
info<!-- >@_ -->@<!-- >@_ -->audiCal<!-- >@_ -->.<!-- >@_ -->net
</td>
<td align="right">
&nbsp;
</td>
</tr></tbody>
</table>

我正在使用 beautifulsoup 来解析这个,但现在我在从最后四个 &lt;td&gt; 获取数据时遇到了问题。每当我使用.string 属性读取它们的值时,我都会得到None 作为值。我猜这是因为他们有&lt;br&gt; 标签。我想要最后四个&lt;td&gt; 具有地址、电话号码、email_id 和传真的数据。我应该使用什么来获取所有这些数据,而不是 .string

【问题讨论】:

    标签: python html-parsing beautifulsoup


    【解决方案1】:

    您可以使用.text 获取文本。

    编辑:

    另一种选择可能是使用.contents 获取每个元素并在必要时加入它们。

    【讨论】:

    • Uisng .text 有效,但它给了我
      4747744747
      108388383 为 4747744747108388383,我希望它是 4747744747,108388383:|
    【解决方案2】:

    一旦你有了td 元素的句柄,你就可以使用:

     td.findAll(text=True) 
    

    获取td 标记的文本子元素列表。然后你可以join,上的那个列表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      相关资源
      最近更新 更多