一、數據獲取—Spider()
1.1 找目標網站,該網站是你看小說的網站,分析該網站的結構方便你對內容的抓取 這裏我獲取最新章節的時間、標題以及標題的連接 這裏獲取內容
1.2編寫spider方法,確定他的返回值,這裏我返回的是一個list,包括更新的時間、標題、內容- 方法中需要導入的包 requests bs4 re
def spider():
list = []
response = requests.get('https://www.xbiquge6.com/13_13134/')
response.encoding = ('utf-8')
html = response.text
html = BeautifulSoup(html, 'html.parser')
time = html.select('div#info p:nth-of-type(3)').__getitem__(0).text[5:]
title = html.select('div#info p:nth-of-type(4) a[href]').__getitem__(0).text
href = html.select('div#info p:nth-of-type(4) a[href]').__getitem__(0)
# print(title)
pattern = re.compile(r'href="(.+?)"')
href = re.findall(pattern, href.__str__()).__getitem__(0)
href = "https://www.xbiquge6.com" + href
response = requests.get(href)
response.encoding = ('utf-8')
html = BeautifulSoup(response.text, 'html.parser')
content = html.select('div#content')
# print(content)
list.append(title)
list.append(content)
list.append(time)
return list
二、郵件發送—smtp()
2.1首先先在你的郵箱中設置打開smtp服務比如我的QQ郵箱,先進入郵箱->點擊設置->點擊賬戶->下滑找到smtp服務->點擊開啓服務->生成授權碼(就是你在smtp方法中用到的password)
2.2編寫smtp方法,向我的郵箱發送小說,確定返回值是bool類型,成功爲True,失敗爲False
def mail():
list = spider();
ret = True
try:
mail_msg = list.__getitem__(1).__str__()
msg = MIMEText(mail_msg, 'html', 'utf-8')
msg['From'] = formataddr(['huzai', my_sender])
msg['To'] = formataddr(['huzai', receiver])
msg['Subject'] = list.__getitem__(0)
server = smtplib.SMTP_SSL('smtp.qq.com', 465)
server.login(my_sender, my_pwd)
server.sendmail(my_sender, [receiver], msg.as_string())
server.quit()
except Exception:
ret = False
return ret
三、上傳腳本到服務器
3.1使用xftp將寫好的smtp.py上傳到你的雲服務器上直接拖進去就行
3.2這裏注意保證你的服務器上的python版本和你本機一致,且需要的包已經安裝- 如果你的服務器上的版本是2.*的可以運行下面代碼安裝python3bashsudo apt-get remove pythonsudo apt-get install python3sudo apt autoremove
### 用xshell進入服務器試着運行
四、在服務器端設置定時執行
4.1確保你安裝了crontab(ubuntu默認安裝)cron命名解析:執行的時間 + 執行的用戶 + 執行的命令
4.2查看原有的croncat /etc/crontab
4.3編輯你的程序sudo nano /etc/crontab
編寫你的命令,每天14:58給我發送郵件,這裏根據你看的小說的更新時間設置,一天幾更在大約什麼時間等等bash58 14 * * * root python3 smtp.py
編輯好了再次查看cron是否已經寫入,我這裏已經寫入
4.4重啓crontab服務bashservice cron restart
五、 靜靜的等待14:58的到來
查看郵箱- 郵件收到了最新更新的哦