Python beautifulsoup试图删除html标签'span'

时间:2010-03-27 16:19:24

标签: python regex beautifulsoup

我想删除

[<span class="street-address">
            510 E Airline Way
           </span>]

我已使用此清除功能删除介于< >

之间的功能
def clean(val):
 if type(val) is not StringType: val = str(val)
 val = re.sub(r'<.*?>', '',val) 
 val = re.sub("\s+" , " ", val)
 return val.strip()

并生成[ 510 E Airline Way ]

我正在尝试添加“干净”功能以删除字符'['']',基本上我只想获取"510 E Airline Way"

任何人都有任何线索我可以添加到clean函数吗?

谢谢

1 个答案:

答案 0 :(得分:9)

使用re:

>>> import re
>>> s='[<span class="street-address">\n            510 E Airline Way\n           </span>]'
>>> re.sub(r'\[|\]|\s*<[^>]*>\s*', '', s)
'510 E Airline Way'

使用BeautifulSoup:

>>> from BeautifulSoup import BeautifulSoup
>>> s='[<span class="street-address">\n            510 E Airline Way\n           </span>]'
>>> b = BeautifulSoup(s)
>>> b.find('span').getText()
u'510 E Airline Way'

使用lxml:

>>> from lxml import html
>>> s='[<span class="street-address">\n            510 E Airline Way\n           </span>]'
>>> h = html.document_fromstring(s)
>>> h.cssselect('span')[0].text.strip()
'510 E Airline Way'