Python 2.7 BeautifulSoup,电子邮件抓取

时间:2016-09-23 12:56:36

标签: python python-2.7 web-scraping beautifulsoup

希望你们都很好。我是Python新手并使用python 2.7。

我试图仅从此公共网站业务目录中提取mailto:http://www.tecomdirectory.com/companies.php?segment=&activity=&search=category&submit=Search
我正在寻找的邮件是完整目录中a-z中每个小部件中提到的电子邮件。遗憾的是,该目录没有API。 我使用的是BeautifulSoup,但到目前为止还没有成功 这是我的代码:

import urllib
from bs4 import BeautifulSoup
website = raw_input("Type website here:>\n")
html = urllib.urlopen('http://'+ website).read()
soup = BeautifulSoup(html)

tags = soup('a') 

for tag in tags:
    print tag.get('href', None)

我得到的只是实际网站的网站,例如http://www.tecomdirectory.com与其他href,而不是小部件中的mailto或网站。我也尝试用汤('目标')代替汤(' a'),但没有运气!请有人帮帮我吗?

1 个答案:

答案 0 :(得分:1)

你不能只找到每个锚,你需要在href中专门寻找“mailto:”,你可以使用一个css选择器a[href^=mailto:]找到 anchor 标签,它们有一个< em> href 以mailto:开头:

import requests

soup  = BeautifulSoup(requests.get("http://www.tecomdirectory.com/companies.php?segment=&activity=&search=category&submit=Search").content)

print([a["href"] for a in soup.select("a[href^=mailto:]")])

或提取文字:

print([a.text for a in soup.select("a[href^=mailto:]")])

使用find_all("a"),您需要使用正则表达式来实现相同的目标:

import re

find_all("a", href=re.compile(r"^mailto:"))
相关问题