2015-06-04 3 views
3

Вот мой HTML код теперь я хочу извлечь данные из следующей HTML-код с помощью красивого супаBeautiful Soup: Получить текстовые данные из HTML

<tr class="tr-option"> 
<td class="td-option"><a href="">A.</a></td> 
<td class="td-option">120 m</td> 
<td class="td-option"><a href="">B.</a></td> 
<td class="td-option">240 m</td> 
<td class="td-option"><a href="">C.</a></td> 
<td class="td-option" >300 m</td> 
<td class="td-option"><a href="">D.</a></td> 
<td class="td-option" >None of these</td> 
</tr> 

здесь моего красивого код супа

soup = BeautifulSoup(html_doc) 
for option in soup.find_all('td', attrs={'class':"td-option"}): 
    print option.text 

выхода код выше:

A. 
120 m 
B. 
240 m 
C. 
300 m 
D. 
None of these 

, но я хочу следующий вывод

A.120 m 
B.240 m 
C.300 m 
D.None of these 

Что мне делать?

ответ

1

Поскольку find_all возвращает список опций, вы можете использовать списочные, чтобы получить ответ, как вы ожидаете

>>> a_list = [ option.text for option in soup.find_all('td', attrs={'class':"td-option"}) ] 
>>> new_list = [ a_list[i] + a_list[i+1] for i in range(0,len(a_list),2) ] 
>>> for option in new_list: 
...  print option 
... 
A.120 m 
B.240 m 
C.300 m 
D.None of these 

Что он делает?

  • [ a_list[i] + a_list[i+1] for i in range(0,len(a_list),2) ] принимает соседние элементы из a_list и добавляет их.
0
soup = BeautifulSoup(html_doc) 
options = soup.find_all('td', attrs={'class': "td-option"}) 
texts = [o.text for o in options] 
lines = [] 
# Add every two-element pair as a concatenated item 
for a, b in zip(texts[0::2], texts[1::2]): 
    lines.append(a + b) 
for l in lines: 
    print(l) 

дает

A.120 m 
B.240 m 
C.300 m 
D.None of these