漂亮汤:从HTML中获取文本数据

3

这是我的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

我该怎么做?

2个回答

2

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接