2011-04-23 66 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

相关问题