解析html美丽的汤

时间:2010-10-02 18:29:15

标签: python regex beautifulsoup

我有一个HTML页面

<a email="corporate@max.ru" href="http://www.max.ru/agent?message&to=corporate@max.ru" title="Click herе" class="mf_spIco spr-mrim-9"></a><a class="mf_t11" type="booster" href="http://max.ru/mail/corporate/">

我需要一个解析电子邮件字符串

    soup = BeautifulSoup(data
    string = soup.find("a",{"email": ""})
    print string

但它不起作用。 哪里有错?

1 个答案:

答案 0 :(得分:4)

您的错误在于使用attrs dict查找电子邮件属性为空的元素。试试这个。

#!/usr/bin/env python

from BeautifulSoup import BeautifulSoup
import urllib2

req = urllib2.urlopen('http://worldnuclearwar.ru')

soup = BeautifulSoup(req)
print soup.find("a", email=True)["email"]

打印具有email属性的第一个 a元素的email属性。如果您想要所有电子邮件,请尝试

for link in soup.findAll("a", email=True):
    print link["email"]