python爬虫爬取网站邮箱电话等
-
目标:
1. 通过爬取网页,分析邮箱,电话,等,进行记录到数据,自动爬门户网站外链,并访问对方网站,获取网站上的相关信息,并记录到数据库 2. 能够自动发送邮件,或短信到收集的数据邮箱里
第一步:实现采集单网页的数据
分采集页面和数据库连接页面
采集页面代码(用的是python2.7):
# encoding: utf-8
import urllib2
import re
import chardet
import sys
import chain_mysql
# 爬取的目标网页上的邮箱地址
# 数据写入文件
def writeData(listData):
chain_mysql.dbInsert(listData)
def outputemail(url):
listReturn = {}
# 使用urllib打开该地址
responseobject = urllib2.urlopen(url)
# 验证输出
#print(requestobject)
# 获取解析的数据
html = responseobject.read()
typeEncode = sys.getfilesystemencoding() ##系统默认编码
infoencode = chardet.detect(html).get('encoding', 'utf-8') ##通过第3方模块来自动提取网页的编码
if infoencode is None:
infoencode = "gb2312"
html = html.decode(infoencode, 'ignore').encode('utf-8') ##先转换成unicode编码,然后转换系统编码输出
# 输入验证获取的内容
#return html
# 使用正则解析文档中存在的email地址
phone=str(re.findall(r"1\d{10}\D",html))
phone =re.findall(r"1\d{10}",phone)
phone=list(set(phone))
title=re.search('<title.*?>.*?</title>', html).group()
pattern = re.compile(r'\s|\n|<title>|</title>', re.S)
title = str(title)
title = pattern.sub('', title)
#nametitle = re.findall('>.*?<',title)
#title=pre.findall(title)
contacturl = re.findall('<a.*? .*?>.*?联系我们.*?</a>', html)
emaillist = re.findall("\w+@\w+\.\w+", html)
emaillist = list(set(emaillist))
listReturn['title'] = title
listReturn['url']=url
listReturn['value']=contacturl
listReturn['email']=emaillist
listReturn['phone']=phone
# 处理超链接中的邮箱地址
# 循环输入email的结果
#for email in emaillist:
# print(email)
return listReturn
listData=[]
# 构造url地址
url = "http://www.klineng.com"
# 把这个功能封装成一个函数
showdata=outputemail(url)
writeData(showdata)
for data in showdata['value']:
cturl = re.search('/.*?\"', data)
if cturl is None:
cturl=""
else:
cturl=cturl.group()
pattern = re.compile(r'\"', re.S)
cturl = pattern.sub('', cturl)
cturl = url+ cturl
writeData(outputemail(cturl))
第二步:创建数据库及数据表,建立连接文件
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
def dbInsert(listData):
# 打开数据库连接
db = MySQLdb.connect("localhost", "root", "1234", "testmail", charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
#for data in listData:
strdata=""
emaildata=""
calldata=""
for data in listData['value']:
strdata = strdata+data+'|'
for maildata in listData['email']:
emaildata = emaildata+maildata+'|'
for phonedata in listData['phone']:
calldata = calldata+phonedata+'|'
# SQL 插入语句
sql = """INSERT INTO t_data (title,url,value,email,phone) VALUES ('""" + listData['title'] + """','""" + str(listData['url'])+ """','""" + strdata + """','""" + emaildata + """','""" + calldata + """')"""
try:
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# 关闭数据库连接
db.close()
实现单网页采集数据功能,并做数据去重,由于页面html代码不一致,对采集数据方面还要进一步完善