2014-10-19 40 views
-1

我想解析一個HTML文檔,並想知道如果你們能幫助我。替換類名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> 

我想將td class ='style10'改爲class ='style14'。但是,當我將其更改爲style14時,它不會提取它。所以,「腳本」不會被打印出來。

這裏是我的代碼:

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

for each in search: 
    print each.text 

有沒有辦法做到這一點?

+0

什麼你不能修改類* *後遍歷'search'? – Bakuriu 2014-10-19 16:18:02

+0

如果您只是在循環中打印每個文件,您會得到什麼? – 2014-10-19 17:15:45

回答

1

您正在通過循環一個元素,並且僅列出子元素。由於您選擇的標籤沒有包含更多文字的子元素(<span style="mso-spacerun:yes">元素爲空),因此您看不到任何內容。

只是不循環,以直接文本:

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' 
+0

非常感謝!我不知道我在循環一些空的東西。現在已經修復了。 – 2014-10-20 19:59:24