2011-06-18 4 views
3

j'ai écrit un code pour analyser html, mais le résultat n'a pas été ce que je voulais:html Parsing utilisant BeautifulSoup en Python

import urllib2 
html = urllib2.urlopen('http://dummy').read() 
from BeautifulSoup import BeautifulSoup 
soup = BeautifulSoup(html) 
for definition in soup.findAll('span', {"class":'d'}): 
definition = definition.renderContents() 
print "<meaning>", definition 
for exampleofuse in soup.find('span',{"class":'x'}): 
    print "<exampleofuse>", exampleofuse, "<exampleofuse>" 
print "<meaning>" 

Y at-il sorte de façon que lorsque l'attribut class est « d » ou « x "pour ensuite obtenir la chaîne?

Le code HTML suivant est ce que je veux analyser:

<span class="d">calculated by adding several amounts together</span> 
<span class="x">an average rate</span> 
<span class="x">at an average speed of 100 km/h</span> 
<span class="d">typical or normal</span> 
<span class="x">average intelligence</span> 
<span class="x">20 pounds for dinner is average</span> 

Ensuite, voici le résultat que je veux:

<definition>calculated by adding several amounts together 
    <example_of_use>an average rate</example_of_use> 
    <example_of_use>at an average speed of 100 km/h</example_of_use> 
</definition> 
<definition>typical or normal 
    <example_of_use>average intelligence</example_of_use> 
    <example_of_use>20 pounds for dinner is average</example_of_use> 
</definition> 

Répondre

5

oui, vous pouvez obtenir toutes les portées dans le code HTML , puis pour chaque vérification d'une classe de "d" ou "x", et si oui, imprimez-les.

quelque chose comme ça pourrait fonctionner (non testé):

for span in soup.findAll('span'): 
    if span.find("span","d").string: 
     print "<definition>" + span.find("span","d").string + "</definition>" 
    elif span.find("span","x").string: 
     print "<example>" + span.find("span","x").string + "</example>" 
Questions connexes