2011-04-23 36 views
2

我第一次使用BeautifulSoup並嘗試從湯對象中收集多個數據,例如電子郵件,電話號碼和郵寄地址。如何使用python獲取跨度值,BeautifulSoup

使用正則表達式,我可以識別電子郵件地址。我的代碼找到電子郵件是:

def get_email(link): 
mail_list = [] 
for i in link: 
     a = str(i) 
     email_pattern = re.compile("<a\s+href=\"mailto:([[email protected]]*)\">", re.IGNORECASE) 
     ik = re.findall(email_pattern, a) 
     if (len(ik) == 1): 
       mail_list.append(i) 
     else: 
       pass 
s_email = str(mail_list[0]).split('<a href="') 
t_email = str(s_email[1]).split('">') 
print t_email[0] 

現在,我還需要收集電話號碼,郵寄地址和網址。我認爲在BeautifulSoup中必須有一個簡單的方法來找到這些特定的數據。

示例HTML頁面如下:

<ul> 
    <li> 
    <span>Email:</span> 
    <a href="mailto:[email protected]">Message Us</a> 
    </li> 
    <li> 
    <span>Website:</span> 
    <a target="_blank" href="http://www.abcl.com">Visit Our Website</a> 
    </li> 
    <li> 
    <span>Phone:</span> 
    (123)456-789 
    </li> 
    </ul> 

而且使用BeatifulSoup,我試圖收集電子郵件,網站和電話的跨度值。

在此先感謝。

+1

這是一個良好的開端教程http://www.crummy.com/software/BeautifulSoup/documentation.html#Quick%20Start – demas 2011-04-23 07:51:02

+1

@demas只是解決了讓所有的UL標籤的問題,然後再提取所需的UL只,其工作正常,感謝您的鏈接:) – mushfiq 2011-04-23 08:03:36

+0

請閱讀BeautifulSoup文檔。不知道爲什麼我們應該爲您重複現有和詳細的文檔。如果您有Beautifulsoup的*特定*問題,請回來。 – 2011-04-23 08:37:00

回答

4

您的代碼最明顯的問題是您將表示鏈接的對象轉換回HTML,然後再次用正則表達式解析 - 這忽略了首先使用BeautifulSoup的很多要點。您可能需要使用正則表達式來處理href屬性的內容,但就是這樣。此外,else: pass是不必要的 - 你可以完全放棄它。

下面是一些代碼,不會像你想要什麼,可能是一個有用的起點:

from BeautifulSoup import BeautifulSoup 
import re 

# Assuming that html is your input as a string: 
soup = BeautifulSoup(html) 

all_contacts = [] 

def mailto_link(e): 
    '''Return the email address if the element is is a mailto link, 
    otherwise return None''' 
    if e.name != 'a': 
     return None 
    for key, value in e.attrs: 
     if key == 'href': 
      m = re.search('mailto:(.*)',value) 
      if m: 
       return m.group(1) 
    return None 

for ul in soup.findAll('ul'): 
    contact = {} 
    for li in soup.findAll('li'): 
     s = li.find('span') 
     if not (s and s.string): 
      continue 
     if s.string == 'Email:': 
      a = li.find(mailto_link) 
      if a: 
       contact['email'] = mailto_link(a) 
     elif s.string == 'Website:': 
      a = li.find('a') 
      if a: 
       contact['website'] = a['href'] 
     elif s.string == 'Phone:': 
      contact['phone'] = unicode(s.nextSibling).strip() 
    all_contacts.append(contact) 

print all_contacts 

這將產生每接觸一個字典中找到的列表,在這種情況下,這將僅僅是:

[{'website': u'http://www.abcl.com', 'phone': u'(123)456-789', 'email': u'[email protected]'}] 
+0

感謝您的快速,乾淨的代碼 – mushfiq 2011-04-23 13:47:50

相關問題