2011-06-18 2 views
3

Я написал код для разбора HTML, но результат был не то, что я хотел:Разбор HTML с использованием BeautifulSoup в 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>" 

Есть ли какой-либо образом, что, когда атрибут класса «d» или «х «чтобы получить строку?

Следующий HTML-код, что я хочу, чтобы разобрать:

<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> 

Тогда это результат я хочу:

<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> 

ответ

5

да, вы можете получить все пролеты в HTML , то для каждой проверки для класса «d» или «x», и если они это сделают, напечатайте их.

что-то подобное может работать (непроверенные):

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>" 
Смежные вопросы