preface

When it comes to programmers, most people probably have the impression that they are well-paid, straight, slovenly, nerdy and boring. But are programmers really like that? The answer, of course, is no, they’re just not interested in any of these, but once they hit, they hit the goddess where it hurts. Today xiaobian will bring you a high forced case of love procedures, readers can according to their own situation for appropriate modification, if you think the length of the analysis is too long, you can directly slide to the bottom of the code.



The results









The package required for this program



import requests
from lxml import etree
from bs4 import BeautifulSoup as BS
from selenium import webdriver
import time
import random
import os
import itchat
import datetimeCopy the code


The wechat message format sent every day is as follows:



    message = """Dear {}: Good morning, today is the first {} day you and NGU have been together ~ today he wants to say to you: {} last and most important! """.format("Candy on a motorcycle.", str(inLoveDays), love_word)Copy the code




The first field to fill in here is the title of the person, “inLoveDays” refers to the number of days you have met and been in love.



Love_word is every day for the ta carefully prepared love words content, of course, if you are good at writing can also write their own.



Here is a small series of online love words daquan (embarrassed)









And last but not least! Different pictures of “I love you” everyday!













Program way of thinking



This program can be run in multiple system platforms, the main library used in Selenium, ITchat, Request. The program is mainly divided into two parts of the first data capture, some love words information and picture information. The other is using ItChat to automatically send messages to your girlfriend.





Line information



If you are confident in your writing style, you can write your own love words. Of course, most people’s writing style is relatively poor like me, so at this time we can use the resources on the Internet, such as the following love words website.



http://www.binzz.com/yulu2/3588.htmlCopy the code


When crawling this site, if you use the usual crawling method, namely using the request for the request, you will find that the data obtained by the page is garbled and incomplete. Therefore, in order to facilitate operation, I use Selenium+Chrome automation to crawl, to achieve visible crawl, to obtain the information of the website. Finally, the obtained data is saved in the current directory [love_word. TXT] to facilitate subsequent reading.



Resources of Confession Pictures



In order to accompany this declaration of love process, I went to find some pictures with “I love you” resources. You can search the keyword “I love you” in 360 pictures, we can get a large number of such picture resources.



http://image.so.com/i?q=%E6%88%91%E7%88%B1%E4%BD%A0%E7%94%B5%E5%BD%B1%E5%8F%B0%E8%AF%8D&src=srpCopy the code








Since this link has a certain anti-crawling strategy, we still use Selenium and Chrome to automate the crawling and use BeautifulSoup to parse it. Of course, you can also use your familiar parsing library to parse and save the crawling images in our “Love Pictures”.



Since you’re probably not running this code for the first time, we need to add a statement to determine if the file exists, so if it does, we don’t need to grab the data, we can just read it from the file, and if not, we’ll just run the grab code.



Vindicate program source code



The program is mainly the following functions

def crawl_Love_words():

def getimage():

def isexist(path):

def send_news():

def main():

Copy the code




crawl_Love_words()



This function uses Selenium + xpath to grab the lovetalk site resources and store them in the love_word.txt file in the current directory.



def crawl_Love_words():
   """Return:"""
   browser = webdriver.Chrome()
   print("Grabbing love words...")
   url = "http://www.binzz.com/yulu2/3588.html"
   browser.get(url)
   html = browser.page_source
   Selector = etree.HTML(html)
   love_words_xpath_str = "//div[@id='content']/p/text()"
   love_words = Selector.xpath(love_words_xpath_str)
   for i in love_words:
       word = i.strip("\n\t\u3000\u3000").strip()
       with open(love_word_path, "a") as file:
           file.write(word + "\n")
   print("Love words grab complete")Copy the code




getimage()



This function is used to crawl 360 images with keywords “I love you”, implemented by Selenium+Chrome automated crawling.



def getimage():
   """Grab I love you picture :return:"""
   browser = webdriver.Chrome()
   url='http://image.so.com/i?q=%E6%88%91%E7%88%B1%E4%BD%A0%E7%94%B5%E5%BD%B1%E5%8F%B0%E8%AF%8D&src=srp'
   browser.get(url)
   count=1
   for i in range(2):
       js = "var q=document.documentElement.scrollTop=100000"
       browser.execute_script(js)
       time.sleep(1)
   time.sleep(2)
   response=browser.page_source
   html=BS(response,'lxml')
   imgurls=html.select('img')
   isexist(pic_path)
   for imgurl in imgurls:
       response = requests.get(imgurl['src'])
       image_path=str(count)+'.jpg'
       count+=1
       with open(image_path,'wb') as f:
           f.write(response.content)
           print(str(count)+' success')Copy the code




isexist()



This function is used to judge whether our file exists, if there is directly switch to the folder directory, otherwise, create a folder, and then switch to the folder directory, this function is mainly used to judge whether [love file] exists when capturing picture information.



def isexist(path):
   ""Param path: :return:""
   if not os.path.exists(path):
       os.makedirs(path)
       os.chdir(path)
   else:
       os.chdir(path)Copy the code


send_new()



This function uses itChat library to automatically send messages to your wechat friends. In this function I use the Datetime module to calculate the time between you and the ta. And I added a [hotReload=True], also called hot boot, when I logged in. This way you don’t have to log in every time you run the program.

def send_news():
   """Send a message and picture to your loved one :return:"""
   # Count the number of days
   inLoveDate = datetime.datetime(2016, 5, 30)  # Time in love
   todayDate = datetime.datetime.today()
   inLoveDays = (todayDate - inLoveDate). Days Wordsnumber = random. Randint (1120).# Random love words

   # Get sweet nothings
   file_path = love_word_path
   with open(file_path) as file:
       love_word = file.readlines()[Wordsnumber].split(':')[1]

   itchat.auto_login(hotReload=True)  # Hot start, no need to scan code multiple login
   my_friend = itchat.search_friends(name=u'Sugar on a motorcycle')
   girlfriend = my_friend[0]["UserName"]
   print(girlfriend)
   message = """Dear {}: Good morning, today is the first {} day you and NGU have been together ~ today he wants to say to you: {} last and most important! """.format("Candy on a motorcycle.", str(inLoveDays), love_word)
   itchat.send(message, toUserName=girlfriend)

   files = os.listdir(pic_path)
   print(files)
   file = files[Wordsnumber]
   print(file)
   love_image_file = "./ "/" + file
   try:
       itchat.send_image(love_image_file, toUserName=girlfriend)
   except Exception as e:
       print(e)Copy the code


main()



This function is mainly used to run the above three functions, and determine whether the resources we need exist, if there is directly from the file can be extracted, otherwise run the function.



def main():
   if os.path.exists(love_word_path):
       print('Love words already exist')
   else:
       crawl_Love_words()

   if os.path.exists(pic_path):
       print('Image already exists')
   else:
       getimage()
   send_news()Copy the code




Timing task



With timed tasks, you can select the time you want to send sweet words and pictures to your beloved. If you don’t need timed messages, you can skip this code and just run main().

if __name__ == '__main__':
   while True:
       curr_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
       love_time = curr_time.split("") [1]if love_time == "13:14:00":
           main()
           time.sleep(60)
       else:
           print("It's not time to show your love, now it's time:" + love_time)Copy the code




Show love program use tutorial



First of all, you need to download the corresponding source code, and the background reply “vindicate” can be obtained. Secondly, install the corresponding library in advance, and then run the program will display a Two-Dimensional code of wechat web login, scanning login can be. As I mentioned earlier, the app has a hot start, so you can send a message each time you run it without having to scan the QR code multiple times.



conclusion



There are many place to extend the program, for example, you can add anything you like elements in, and if you think you have been running on their host is a very troublesome thing, so your application can be deployed to the server, in a word, I give you code, the goddess of the heart can save you.



This article was first published on the public account [TWcoding]. For those who are interested in Python, crawlers, data analysis and algorithms, please add the wechat public account [TWcoding] and let’s play Python together. Python 2018 is the latest Python resource.



If it works for you.Please,star.



God helps those who help themselves



Automatic identification of http://weixin.qq.com/r/Tyo7I4jE3NWjrcxA939d (qr code)