Python 2.7 BeautifulSoup,电子邮件抓取

标签 python python-2.7 web-scraping beautifulsoup

希望你一切都好。我是 Python 新手,使用的是 python 2.7。

我试图从这个公共(public)网站业务目录中仅提取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'),但没有运气!有人可以帮我吗?

最佳答案

你不能只找到每个 anchor ,你需要在href中专门查找“mailto:”,你可以使用css选择器a[href^=mailto:]来查找具有以 mailto::

开头的 href 的 anchor 标记
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:"))

关于Python 2.7 BeautifulSoup,电子邮件抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39661367/

相关文章:

python - 在没有 Tee 的情况下在 Python 中克隆生成器

python - .kv 和 python 代码中的变量不同步

python - 使用错误版本的 Python 的 Github 操作

python - Django/Tastypie - DELETE 请求删除所有内容

node.js - 关于简单命令行网络爬虫(Clojure/ClojureScript)的一些问题

python - 我想用 z 矩阵所有值的平均值填充 z 矩阵中的缺失值

python - 使用 python 子进程将文件从 .sam 转换为 .bam

python - 如何加载网页(不在浏览器中)然后获取该网页的网址?

python - 我的 Scrapy CrawlSpider 在初始启动 URL 后停止

python - 如何使用 BeautifulSoup 从所有脚本中提取正确的脚本