【问题标题】:Replacing class name BeautifulSoup替换类名 BeautifulSoup
【发布时间】:2014-10-19 16:11:23
【问题描述】:

我正在尝试解析 HTML 文档,想知道你们是否可以帮助我。

<tr height="21" style="height:15.75pt">
       <td class="style14" height="21" style="height: 15.75pt">
        71
       </td>
       <td class="style14">
        Breakeven
       </td>
       <td class="style10">
        The Script
        <span style="mso-spacerun:yes">
        </span>
       </td>
      </tr>

我想将 td class='style10' 更改为 class='style14'。但是,当我将其更改为 style14 时,它并没有拾取它。所以,“剧本”没有被打印出来。

这是我的代码:

search =soup.find('td', class_='style10')
search['class'] = 'style14'

for each in search: 
    print each.text

有没有办法做到这一点?

【问题讨论】:

  • 在迭代search 之后 不能修改什么类?
  • 如果你只打印循环中的每一个,你会得到什么?

标签: python beautifulsoup


【解决方案1】:

您正在循环一个元素,并且只列出子元素。因为您选择的标签没有包含更多文本的子元素(&lt;span style="mso-spacerun:yes"&gt; 元素为空),所以您看不到任何内容。

只是不要循环,直接进入文本:

print search.text

你的班级变化并没有破坏这里的任何东西。

演示:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''\
... <tr height="21" style="height:15.75pt">
...        <td class="style14" height="21" style="height: 15.75pt">
...         71
...        </td>
...        <td class="style14">
...         Breakeven
...        </td>
...        <td class="style10">
...         The Script
...         <span style="mso-spacerun:yes">
...         </span>
...        </td>
...       </tr>
... ''')
>>> search =soup.find('td', class_='style10')
>>> search['class']
['style10']
>>> search['class'] = 'style14'
>>> search['class']
'style14'
>>> list(search)
[u'\n        The Script\n        ', <span style="mso-spacerun:yes">
</span>, u'\n']
>>> search.text
u'\n        The Script\n        \n\n'

【讨论】:

  • 非常感谢!我不知道我正在循环一些空的东西。现在已经修好了。
猜你喜欢
  • 2019-06-22
  • 2017-01-10
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
相关资源
最近更新 更多