使用beautifulsoup </b>从html中的<b>标签中提取文本

时间:2013-03-21 03:32:24

标签: python html beautifulsoup text-extraction

这是html代码中表示我想从网页中提取的信息的部分。我的目的是只提取b标签之间的名称和值。我期望的结果是这样的列表:[On,DVI,396,2035,2551]

 ...   
<div class="txt"><br> 
Power: <b>On</b><br><br>
Source: <b>DVI</b><br><br>
Lamp runtime: <b>396</b> hours<br>
Lamp remaining: <b>2035</b> hours<br>
Total operation: <b>2551</b> hours<br>
</div>
...

我尝试的是:

from bs4 import BeautifulSoup
import urllib2
url='ip address here'
html=urllib2.urlopen(url).read()
soup=BeautifulSoup(html)
main_div=soup.find("div",{"class":"txt"})
data=main_div.findAll('b').text

出了什么问题?仅供参考,我是初学者,请耐心等待。

2 个答案:

答案 0 :(得分:2)

data=[b.string for b in main_div.findAll('b')]

答案 1 :(得分:2)

也许是这样的?

import BeautifulSoup

html = '''<div class="txt"><br> 
\nPower: <b>On</b><br><br>
\nSource: <b>DVI</b><br><br>
\nLamp runtime: <b>396</b> hours<br>
\nLamp remaining: <b>2035</b> hours<br>
\nTotal operation: <b>2551</b> hours<br>
\n</div>'''

soup = BeautifulSoup.BeautifulSoup(html)
bTags = [] 

for i in soup.findAll('b'):
    bTags.append(i.text)

bTags的内容:

[u'On', u'DVI', u'396', u'2035', u'2551']