# Author:Nimo_Ding
'''
练习介绍:
在第3关的一个课后练习里,我们爬取了指定电影的下载链接;在第6关的一个课后练习里,我们存储了豆瓣TOP250的榜单信息。
现在,我们完善这个程序,每周五在存储的榜单中,随机抽三部电影,然后去爬取这三部电影的下载链接,并把链接的结果发送到邮箱。
'''
import requests,random,csv,smtplib,schedule,time
from bs4 import BeautifulSoup
from urllib.request import quote
from email.mime.text import MIMEText
from email.header import Header
account = '***@qq.com'
password = '***'
receiver = '***@qq.com'
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'
}
dic = {}
def top250movies():
for x in range(2): # 这里只取了前两页电影数据
url = 'https://movie.douban.com/top250?start=' + str(x*25) + '&filter='
res=requests.get(url,headers=headers)
soup=BeautifulSoup(res.text,'html.parser')
for i in soup.find(class_='grid_view').find_all('li'):
dic[i.find('em').text]=i.find('span',class_='title').text
return(dic)
def random_3movies():
top250movies()
movies_list=[]
movies_info=''
while len(movies_list)<3:
movie=dic[str(random.randint(1,50))]
gbk_movie = movie.encode('gbk')
url = "http://s.ygdy8.com/plus/s0.php?typeid=1&keyword=" + quote(gbk_movie)
res = requests.get(url)
res.encoding = 'gbk'
soup_movie = BeautifulSoup(res.text,'html.parser')
urlpart = soup_movie.find(class_='co_content8').find_all('table')
if urlpart == []:
continue
else:
movies_list.append('test')
urlmovie = 'https://www.ygdy8.com/' + urlpart[0].find('a')['href']
res1 = requests.get(urlmovie)
res1.encoding = 'gbk'
soup_movie1 = BeautifulSoup(res1.text, 'html.parser')
urldownload = soup_movie1.find('div', id='Zoom').find('span').find('table').find('tbody').find('a')['href']
movies_info=movies_info+'\n'+('推荐电影:{}\n网页链接为:{}\n下载链接为:{}\n'.
format(movie, url, urldownload))
return movies_info
def mail():
mailhost='smtp.qq.com' # QQ邮箱服务器地址
qqmail=smtplib.SMTP() # 实例化smtplib模块里的SMTP类的对象,就可以调用SMTP对象的方法了。
qqmail.connect(mailhost,25) # 连接服务器(服务器地址,SMTP端口号),端口号的选择不是唯一的,但25是最简单最基础的端口号。
account1 = account
password1 = password # 这是邮箱的授权码,不是邮箱密码
qqmail.login(account1,password1)
receiver1=receiver
content=random_3movies()
message=MIMEText(content,'plain','utf-8') # 构造一个纯文本邮件。
subject = '电影下载链接'
message['From'] = Header(account)
message['To'] = Header(receiver)
message['Subject']=Header(subject,'utf-8')
try:
qqmail.sendmail(account1,
receiver1,
message.as_string())
print('邮件发送成功!')
except:
print('邮件发送失败!')
qqmail.quit()
# schedule.every().Friday.at("18:00").do(mail) # 每周五18:00执行计划。
schedule.every(10).seconds.do(mail)
while True:
schedule.run_pending()
time.sleep(1)