冬日,电暖风开了一整夜,早上起来嗓子干的简直要爆炸,便寻思着是时候关爱一下空气加湿器厂商了。逛遍天猫,着实不便宜,于是扭头看一下我心爱的券站。一看吓一跳啊,立减40元啊!按耐着我激动澎湃的心情点进去,再点进去,输入账号密码领券,感觉马上能省一个亿,突然被提示优惠券已被领光!!!!
伪程序员生气了,后果就是尝试用弱鸡的编程知识尝试貌似高大上的解决方法。
一、用BeautifulSoup爬取目标网页内容;然后就爬取结果遍历切片;切片结果逐个和输入的内容比照;比照如果一致,将商品名称、链接另行追加赋值给另一字符串。
search.py
from bs4 import BeautifulSoup
import urllib.request
neirong=input("想买的东西:")
z=len(neirong)
string3=''
url = 'http://www.kiees.com'
request = urllib.request.Request(url)
response = urllib.request.urlopen(request, timeout=20)
content = response.read()
soup = BeautifulSoup(content, 'html.parser',from_encoding='utf-8')
links=soup.find_all('h2')
for link in links:
string1=str(link.a.get_text())
x=len(string1)
for y in range(0,x):
if neirong==string1[y:y+z]:
#print(string1)
string2='www.kiees.com'+link.a['href']
#print(string2)
string3=string3+string1+string2+'\n'
#print(string3)
continue
二、比照结束后,对字符串进行判断,如果为空,则未找到相关商品;如果找到,则发送商品信息至邮箱。
send123.py
#!/usr/bin/env python3
#coding: utf-8
import smtplib
import search
from email.mime.text import MIMEText
from email.header import Header
sender = 'after_sunday@126.com'
receiver = 'after_sunday@126.com'
subject = '您关注的特价物品'
smtpserver = 'smtp.126.com'
username = 'a**********y'
password = '***********'
def sendmail123(abcd):
msg = MIMEText(abcd,'text','utf-8')#中文需参数‘utf-8’,单字节字符不需要
msg['Subject'] = Header(subject, 'utf-8')
smtp = smtplib.SMTP()
smtp.connect('smtp.126.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
if search.string3!='':
sendmail123(search.string3)
print('邮件发送成功')
else:
print('没找到商品')
下一步,添加一个无限循环,计时执行的功能,并添加开机运行和后台执行。这样就不怕错过优惠券了!