簡體   English   中英

美麗的湯 - 處理錯誤

[英]Beautiful Soup - handling errors

  1. 我想知道如何處理<strong>Text:</strong>href不存在的情況

  2. 有沒有更好的方法來搜索<strong>Contact:</strong>之后存在的內容

http://pastebin.com/FYMxTJkf

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是在標簽后面返回空格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM