最近因為支付寶送了我個紅包,可以買基金,又看了一些基金的文章,想買點基金玩玩,在知乎上看到這樣一篇文章:
其實如果是長期定投,用簡單的方法篩選即可:
晨星近5年、近3年評級為五星;
天天的業績排名近3年、2年、1年、6個月的業績都為優秀;
基金經理人在近3年無更換。
然後我就想及時知道我買的基金的經理人有沒有換,併發郵件來用通知我。所以有了下面這段程式
import requests
from bs4 import BeautifulSoup
url = `http://fund.eastmoney.com/000311.html?spm=search`
request = requests.get(url)
request.encoding = `utf-8` #有時會亂碼
result = request.text
html = BeautifulSoup(result,"lxml") #解析
titel = html.select_one("#body div.fundDetail-main > div.fundInfoItem > div.infoOfFund td:nth-of-type(3) a") #select返回的是一個列表
name = titel.get_text().strip()
print(name)
if name != "黎海威":
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 三個引數:第一個為文字內容,第二個 plain 設定文字格式,第三個 utf-8 設定編碼
msg = MIMEText(`景順長城滬深300增強(000311):基金經理有變動,已不是黎海威!請查收。`, `plain`, `utf-8`)
# 輸入Email地址和口令:
from_addr = `XXX@163.com`
password = `XXX`
# 輸入SMTP伺服器地址:
smtp_server = `smtp.163.com`
# 輸入收件人地址:
to_addr = `XXX@qq.com,XXX@qq.com`
msg[`From`] = from_addr
msg[`To`] = to_addr
msg[`Subject`] = `基金經理變更`
server = smtplib.SMTP(smtp_server, 25) # SMTP協議預設埠是25
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, to_addr.split(`,`), msg.as_string()) ##發給多個人
server.quit()
第二版:爬取多個基金
#====================================第二版=========================================
import requests
from bs4 import BeautifulSoup
#郵件
import smtplib
from email.mime.text import MIMEText
from email.header import Header
names_pc=[] #爬蟲下來的名字
fundnames = [`景順長城滬深300增強(000311)`,`興全滬深300指數(LOF)(163407)`]
names_pass = [`黎海威`, `申慶`]
stock_code = [`000311`,`163407`]
urls =[]
for i in stock_code:
url = `http://fund.eastmoney.com/`+str(i)+`.html?spm=search`
urls.append(url)
for url in urls:
request = requests.get(url)
request.encoding = `utf-8` #有時會亂碼
result = request.text
html = BeautifulSoup(result,"lxml") #解析
titel = html.select_one("#body div.fundDetail-main > div.fundInfoItem > div.infoOfFund td:nth-of-type(3) a") #select返回的是一個列表,用select的話用[0]可以
name = titel.get_text().strip()
print(name)
names_pc.append(name)
print(names_pc)
from_addr = `XXXX@163.com`
password = `XXXX`
smtp_server = `smtp.163.com` # 輸入SMTP伺服器地址:
to_addr = `XXX@qq.com,XXX@qq.com` # 輸入收件人地址:
for name_pc,name_pass,fundname in zip(names_pc,names_pass,fundnames):
if name_pc != name_pass:
text = `{}:基金經理有變動,已不是{}!請查收`.format(fundname,name_pass)
msg = MIMEText(text, `plain`, `utf-8`)
msg[`From`] = from_addr
msg[`To`] = to_addr
msg[`Subject`] = `基金經理變更` ##主題
server = smtplib.SMTP(smtp_server, 25) # SMTP協議預設埠是25
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, to_addr.split(`,`), msg.as_string()) ##發給多個人
server.quit()
定時任務
既然已經寫好程式了,當然希望它每天能跑,然後我就去阿里雲租了臺伺服器
輸入crontab -e
來執行定時任務,注意上面的程式在阿里雲上需要將smtplib.SMTP
函式改成smtplib.SMTP_SSL來執行才能跑通
0 10 * * * /usr/bin/python3 /home/admin/fund/fundchange2email_v1.py > /home/admin/fund/fund.log
再ctrl+x
儲存並退出