Beautiful Soup - 处理错误

0 投票
1 回答
1061 浏览
提问于 2025-04-17 02:15
  1. 我想知道如果在 <strong>Text:</strong> 后面没有 href 的话该怎么处理。

  2. 有没有更好的方法来查找在 <strong>Contact:</strong> 后面存在的内容?

http://pastebin.com/FYMxTJkf

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"

如果你特别想找一个带有 hrefa 标签,可以使用:

contact = label.findNext('a', attrs={'href' : True})

这样你就不需要去处理空格了。我想你之前这么做是因为 next 方法返回了标签后面的空格。

撰写回答