问题
I'm trying to parse an HTML document, and was wondering if you guys can help me out.
<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>
I would like to change td class= 'style10' to class='style14'. However, when I change it to style14, it does not pick it up. So, "The Script" doesn't get printed.
Here's my code:
search =soup.find('td', class_='style10')
search['class'] = 'style14'
for each in search:
print each.text
Is there a way to do this?
回答1:
You are looping over one element, and that only lists child elements. Because your selected tag has no child elements with further text (the <span style="mso-spacerun:yes">
element is empty), you don't see anything.
Just don't loop, get to the text directly:
print search.text
Your class change didn't break anything here.
Demo:
>>> 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'
来源:https://stackoverflow.com/questions/26452492/replacing-class-name-beautifulsoup