本文主要是介绍每天定时给你的女朋友发送睡前小故事其一,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这是一个爬取故事,每天定时发送的案例,发送给谁呢?可以发送给自己的女朋友,什么?不可能有女朋友?那就好好练习一下代码,学会之后说不准哪天就用到了,不对吗?
代码主要分成两部分,第一部分是爬取故事网站,然后把故事的连接保存到文件中。代码部分如下
def request_html(self,url,title_url):response = requests.get(url=url,headers=self.headers).content.decode('utf-8')tree = etree.HTML(response)title = tree.xpath('.//div[@id="Mhead2_0"]//dd//a/text()')href = tree.xpath('.//div[@id="Mhead2_0"]//dd//a/@href')href = ["http://www.tom61.com"+hre for hre in href]for t,h in zip(title,href):dict_story = {}dict_story[t] = htitle_url.append(dict_story)print(title_url)# json_str = json.dumps(title_url,ensure_ascii=False)with open('故事.json','w',encoding='utf-8') as f:json.dump(title_url,f,ensure_ascii=False)#爬取小故事def crawlStory(self,endpage):title_url = []url = 'http://www.tom61.com/ertongwenxue/shuiqiangushi/index.html'self.request_html(url,title_url)for i in range(2, endpage):url = 'http://www.tom61.com/ertongwenxue/shuiqiangushi/index_%s.html' % (i)self.request_html(url,title_url)
第二部分则是获取url,然后解析,把故事发送到她的邮箱中的代码,代码如下
#发送小故事到邮箱当中def sendStory(self):with open(r'F:\reptile\第二周\第五天\故事.json', 'r', encoding='utf-8') as f:content = f.read()story = json.loads(content)story_url = random.choice(story)for k, v in story_url.items():name = kurl = vresponse = requests.get(url=url, headers=self.headers).content.decode('utf-8')tree = etree.HTML(response)content_list = tree.xpath('.//div[@class="t_news_txt"]//text()')content = "\n".join(content_list)print(content)self.sendemail(name,content,'66666666@qq.com')# 发送邮箱的函数def sendemail(self,subject,content,recver):subject = subject # 邮件主题content = content # 邮件内容sender = "88888888@qq.com" # 发送者的邮箱recver = recver # 接收者的邮箱,可以是一个也可以是多个,多个的话要使用recver.split(",\n")转换格式password = "xxxxxxxxxxxxxx" # 授权码部分message = MIMEText(content, "plain", "utf-8") # 设置格式,加入邮件内容message["Subject"] = subjectmessage["To"] = recvermessage["From"] = sendertry:smtp = smtplib.SMTP_SSL("smtp.qq.com", 465) # 使用的服务器和端口,可以是qq的也可以是163的smtp.login(sender, password) # 登录邮箱smtp.sendmail(sender, recver.split(",\n"), message.as_string()) # 发送邮件smtp.close() # 关闭服务器print('发送成功')except:print('出现异常')
完整的代码如下
import requests
from fake_useragent import UserAgent
from lxml import etree
import json
import smtplib # 登陆邮件服务器,进行邮件发送
from email.mime.text import MIMEText # 负责构建邮件格式
import randomclass Story():def __init__(self):self.ua = UserAgent()self.useragent = self.ua.randomself.headers = {'User-Agent': self.useragent}#爬取保存小故事到文件中def request_html(self,url,title_url):response = requests.get(url=url,headers=self.headers).content.decode('utf-8')tree = etree.HTML(response)title = tree.xpath('.//div[@id="Mhead2_0"]//dd//a/text()')href = tree.xpath('.//div[@id="Mhead2_0"]//dd//a/@href')href = ["http://www.tom61.com"+hre for hre in href]for t,h in zip(title,href):dict_story = {}dict_story[t] = htitle_url.append(dict_story)print(title_url)# json_str = json.dumps(title_url,ensure_ascii=False)with open('故事.json','w',encoding='utf-8') as f:json.dump(title_url,f,ensure_ascii=False)#爬取小故事def crawlStory(self,endpage):title_url = []url = 'http://www.tom61.com/ertongwenxue/shuiqiangushi/index.html'self.request_html(url,title_url)for i in range(2, endpage):url = 'http://www.tom61.com/ertongwenxue/shuiqiangushi/index_%s.html' % (i)self.request_html(url,title_url)#发送小故事到邮箱当中def sendStory(self):with open(r'F:\reptile\第二周\第五天\故事.json', 'r', encoding='utf-8') as f:content = f.read()story = json.loads(content)story_url = random.choice(story)for k, v in story_url.items():name = kurl = vresponse = requests.get(url=url, headers=self.headers).content.decode('utf-8')tree = etree.HTML(response)content_list = tree.xpath('.//div[@class="t_news_txt"]//text()')content = "\n".join(content_list)print(content)self.sendemail(name,content,'66666666@qq.com')# 发送邮箱的函数def sendemail(self,subject,content,recver):subject = subject # 邮件主题content = content # 邮件内容sender = "88888888@qq.com" # 发送者的邮箱recver = recver # 接收者的邮箱,可以是一个也可以是多个,多个的话要使用recver.split(",\n")转换格式password = "xxxxxxxxxxxxxx" # 授权码部分message = MIMEText(content, "plain", "utf-8") # 设置格式,加入邮件内容message["Subject"] = subjectmessage["To"] = recvermessage["From"] = sendertry:smtp = smtplib.SMTP_SSL("smtp.qq.com", 465) # 使用的服务器和端口,可以是qq的也可以是163的smtp.login(sender, password) # 登录邮箱smtp.sendmail(sender, recver.split(",\n"), message.as_string()) # 发送邮件smtp.close() # 关闭服务器print('发送成功')except:print('出现异常')if __name__ == '__main__':story = Story()# story.crawlStory(3)story.sendStory()
这篇关于每天定时给你的女朋友发送睡前小故事其一的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!