使用BeautifulSoup提取字符串的部分

时间:2014-12-12 10:44:26

标签: python beautifulsoup

我正在使用Beautiful Soup 4来解析html文档并提取数据。

我想从这个标签中获取时间值:

<span style="font-size:9.0pt;font-family:Arial;color:#666666"> 20 min <b>Start time: </b> 10 min <b>Other time: </b> 0 min</span>
I.E:20分钟,10分钟

2 个答案:

答案 0 :(得分:2)

这有帮助吗?

from BeautifulSoup import BeautifulSoup
from BeautifulSoup import Tag

soup = BeautifulSoup("<span style=\"font-size:9.0pt;font-family:Arial;color:#666666\"> 20 min <b>Start time: </b> 10 min <b>Other time: </b> 0 min</span>")
span = soup.find('span')
for e in span.contents:
 if type(e) is Tag:
   print "found a tag:", e.name
 else:
   print "found text:", e

输出:

found text:  20 min
found a tag: b
found text:  10 min
found a tag: b
found text:  0 min

答案 1 :(得分:0)

这是应该做的:

from bs4 import BeautifulSoup

ss = """<span style="font-size:9.0pt;font-family:Arial;color:#666666"> 20 min <b>Start time:     </b> 10 min <b>Other time: </b> 0 min</span>"""
soup = BeautifulSoup(ss)
timetext = soup.span.text
start_time = timetext.split("Start time:")[1].split("min")[0].strip()

我已经将提取other_time作为练习了!