Beautiful Soup - 处理错误
我想知道如果在
<strong>Text:</strong>
后面没有href
的话该怎么处理。有没有更好的方法来查找在
<strong>Contact:</strong>
后面存在的内容?
1 个回答
2
那你觉得 findNext 这个方法怎么样呢?
import re
from BeautifulSoup import BeautifulSoup
html = '''<strong>Text:</strong>
<a href='http://domain.com'>url</a>'''
soup = BeautifulSoup(html)
label = soup.find("strong" , text='Text:')
contact = label.findNext('a')
if contact.get('href') != None:
print contact
else:
print "No href"
如果你特别想找一个带有 href
的 a
标签,可以使用:
contact = label.findNext('a', attrs={'href' : True})
这样你就不需要去处理空格了。我想你之前这么做是因为 next
方法返回了标签后面的空格。