如何使用Python和BeautifulSoup获取span值
我第一次使用BeautifulSoup,想从一个“汤”对象中收集一些数据,比如电子邮件、电话号码和邮寄地址。
我用正则表达式找到了电子邮件地址。我的代码是:
def get_email(link):
mail_list = []
for i in link:
a = str(i)
email_pattern = re.compile("<a\s+href=\"mailto:([a-zA-Z0-9._@]*)\">", 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:abc@gmail.com">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>
我正在使用BeautifulSoup,试图收集电子邮件、网站和电话号码的span值。
提前谢谢你。
1 个回答
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'abc@gmail.com'}]