在本地测试成功了。其实,我主要想配置在云服务器上,就完美了!
from selenium import webdriver
import time
import re
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
dict2 = {}
class SsqSpider(object):
driver_path = "D:\chromedriver_win32\chromedriver.exe"
def __init__(self):
self.driver = webdriver.Chrome(executable_path=SsqSpider.driver_path)
self.url = "http://www.cwl.gov.cn/kjxx/ssq/kjgg/"
self.positions = []
def run(self): #运行程序
self.request_detail_page(self.url)
def request_detail_page(self, url): #请求网页,提取想要的信息
self.driver.get(url)
source = self.driver.page_source # 获取当前页面的源代码。包含我们想要的详细信息--彩票相关信息
self.get_details(source)
def get_details(self,source):
global dict2
soup = BeautifulSoup(source, 'lxml')
first = soup.select("body > div.wqkj.ssq > div > div.bgzt > table > tbody > tr:nth-child(1)") #返回的是一个列表。只有1个元素。
first2 = first[0]
# print(first2)
# print(type(first2))
ret = re.findall(r"<span class=\".+?\">(\d+?)</span>", str(first2)) #用正则表达式对这个字符串提取信息。
# ret = re.findall(r"\d",str(first2))
# print(ret) #获取的是6个红球,1个篮球。
#获取开奖日期
date = soup.select("body > div.wqkj.ssq > div > div.bgzt > table > tbody > tr:nth-child(1) > td:nth-child(2)")[0]
# print(date.text)
dict2 = {
"出奖日期": date.text,
"中奖号码,最后一个是篮球":ret
}
# print(dict)
print(dict2)
def sendmail(self,subject, email_text):
email_host = 'smtp.qq.com' # 邮箱地址
email_user = '937758398@qq.com' # 发送者账号
email_pwd = 'ebbbatqfmlosbaid' # 发送者密码
maillist = '15201308426@139.com'
# 收件人邮箱,多个账号的话,用逗号隔开
me = email_user
msg = MIMEText(email_text) # 邮件内容
msg['Subject'] = subject # 邮件主题
msg['From'] = me # 发送者账号
msg['To'] = maillist # 接收者账号列表
smtp = smtplib.SMTP_SSL(email_host, port=465) # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
smtp.login(email_user, email_pwd) # 发送者的邮箱账号,密码
smtp.sendmail(me, maillist, msg.as_string())
# 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
smtp.quit() # 发送完毕后退出smtp
print('email send success.')
if __name__ == "__main__":
spider = SsqSpider()
newest = "位置"
spider.run()
newest = dict2["出奖日期"]
spider.sendmail("双色球彩票刷新了"+dict2["出奖日期"], "号码:" + str(dict2["中奖号码,最后一个是篮球"]))
i=0
while True:
spider.run()
if dict2["出奖日期"] == newest: #如果最新的日期等于 newest当中的数值,
newest = dict2["出奖日期"] #把最新的日期赋值给中间件
print("没有最新的,需要等待")
i = i + 1
print("刷新%s次" % i)
else:
spider.sendmail("最新的彩票刷新了", "出奖日期:" + dict2["出奖日期"] + "======中奖号码:" + str(dict2["中奖号码,最后一个是篮球"]))
print("日期:" + dict2["出奖日期"] + "号码:" + str(dict2["中奖号码,最后一个是篮球"]))
time.sleep(20)