python - 如何使用 python,BeautifulSoup 获取跨度值

标签 python beautifulsoup

我是第一次使用 BeautifulSoup 并尝试从 soup 对象中收集一些数据,例如电子邮件、电话号码和邮寄地址。

使用正则表达式,我可以识别电子邮件地址。我查找电子邮件的代码是:

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>

并且使用 BeatifulSoup,我正在尝试收集电子邮件、网站和电话的跨度值。

提前致谢。

最佳答案

您的代码最明显的问题是您将表示链接的对象转回 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'}]

关于python - 如何使用 python,BeautifulSoup 获取跨度值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5762975/

相关文章:

python - 构建 Boost Python 调试

python - 是否有任何 Python 等效于部分类?

python - 如何根据条件/范围对相似的数字进行分组

python - 在类中加载外部模块时无法加载 apache 服务器

Python SSL 错误 CERTIFICATE_VERIFY_FAILED

python - 重新分配字典值列表

python - 将 beautifulsoup 输出转换为矩阵

html - 如何使用 BeautifulSoup/lxml 将子 DOM 节点合并/折叠到父节点中?

python - 使用BeautifulSoup按id解析

python - BeautifulSoup4 藏在哪里?